Iterating through an array without using a for loop
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (1)
Stephen23
am 3 Jul. 2019
theta = 0:0.1:2*pi/5
theta(:) = rand(1,numel(theta))
3 Kommentare
Stephen23
am 3 Jul. 2019
Bearbeitet: Stephen23
am 3 Jul. 2019
"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
am 3 Jul. 2019
theta(:) = theta(:) + 1
can be abbreviated to
theta = theta + 1;
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!