Iterating through an array without using a for loop

6 次查看(过去 30 天)
I want to index through theta and assign each index a random value without using a forloop. Is there a better and faster way to preallocate theta?
theta = 0:0.1:2*pi/5
theta(1:1:length(theta)) = rand
Right now the code preallocates theta with incements of 0.1 from 0 to 2*pi/5.
Instead of replacing a single index with a random value, the entire array is being replaced with a random value.

回答(1 个)

Stephen23
Stephen23 2019-7-3
theta = 0:0.1:2*pi/5
theta(:) = rand(1,numel(theta))
  3 个评论
Stephen23
Stephen23 2019-7-3
编辑:Stephen23 2019-7-3
"I didn't realize rand(...) had a special format."
You are using rand, which means that you must have read the rand documentation. Guessing how to use MATLAB functions is not reliable or efficient, the documentation is much preferred.
"How would I now add a value of one to each index in the array without a forloop?"
Your terminology is a confusing, because it is unlikely that you want to add "one to each index", most likely you want to add one to the values of the array elements... which is easy to do:
theta(:) = theta(:) + 1
Indices are also just numbers, which can also be added to, but indices are not elements of an array (they are just ways of referring to elements of arrays).

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by