Looping through index number + 1
22 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
JIAN-HONG YE ZHU
am 28 Mär. 2023
Kommentiert: JIAN-HONG YE ZHU
am 28 Mär. 2023
Hello, say I have a cell array called 'group' and I want to loop to do a specific calculation which is the following:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1338324/image.png)
In this case, i goes from 1 to 15 and I am calculating the norm between each cell subarray, 1st row.
So when i = 15, where my code has i+1 this would be 16 and it would exceed the index number of array elements.
What would be the best way to avoid this issue? Using an if statement when i == 15?
Thanks.
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 28 Mär. 2023
This code probably isn't doing what you think it is. I've commented it out below so I could run some code later in this answer.
% for i = (1:size(group))'
The size function called with 1 input returns a vector containing the size of the input in each dimension. When you call the colon operator : with one of the inputs being a vector (rather than a scalar) the operator ignores all elements after the first.
In addition, the colon operator creates a row vector. By transposing it you create a column vector. How does the for keyword handle iterating over a column vector? It uses this syntax from that documentation page: "valArray — Create a column vector, index, from subsequent columns of array valArray on each iteration. " So this loop is only ever going to run 1 iteration (unless group has 0 rows, in which case it won't run at all.)
If you want to iterate over all elements of an array I'd use the numel function instead. Compare v1 and v2 below.
c = {1, 2:3, 4:6, 7:10}
size(c)
v1 = 1:size(c)
numel(c)
v2 = 1:numel(c)
Of course you can perform arithmetic on numel in your loop.
v3 = 1:numel(c)-1
Weitere Antworten (1)
Antoni Garcia-Herreros
am 28 Mär. 2023
Not exactly sure what you are trying to do but, why do you want to loop through all 15 cells? isn't it enough to loop through 14?
for i=1:size(group)-1 % This only loops 14 times
0 Kommentare
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!