Iterating through an array without using a for loop

조회 수: 7 (최근 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 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