Looping through index number + 1

38 views (last 30 days)
Hello, say I have a cell array called 'group' and I want to loop to do a specific calculation which is the following:
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.

Accepted Answer

Steven Lord
Steven Lord on 28 Mar 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}
c = 1×4 cell array
{[1]} {[2 3]} {[4 5 6]} {[7 8 9 10]}
size(c)
ans = 1×2
1 4
v1 = 1:size(c)
v1 = 1
numel(c)
ans = 4
v2 = 1:numel(c)
v2 = 1×4
1 2 3 4
Of course you can perform arithmetic on numel in your loop.
v3 = 1:numel(c)-1
v3 = 1×3
1 2 3
  1 Comment
JIAN-HONG YE ZHU
JIAN-HONG YE ZHU on 28 Mar 2023
Thank you very much for your insight, it was a great explanation.

Sign in to comment.

More Answers (1)

Antoni Garcia-Herreros
Antoni Garcia-Herreros on 28 Mar 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

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!