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.
0 个评论
采纳的回答
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}
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
更多回答(1 个)
Antoni Garcia-Herreros
2023-3-28
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!