Looping through index number + 1

38 次查看(过去 30 天)
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.

采纳的回答

Steven Lord
Steven Lord 2023-3-28
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 个)

Antoni Garcia-Herreros
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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by