Iterating through an array without using a for loop

6 ビュー (過去 30 日間)
Calvin Chang
Calvin Chang 2019 年 7 月 3 日
コメント済み: Walter Roberson 2019 年 7 月 3 日
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).
Walter Roberson
Walter Roberson 2019 年 7 月 3 日
theta(:) = theta(:) + 1
can be abbreviated to
theta = theta + 1;

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by