필터 지우기
필터 지우기

Looping through index number + 1

조회 수: 27 (최근 30일)
JIAN-HONG YE ZHU
JIAN-HONG YE ZHU 2023년 3월 28일
댓글: JIAN-HONG YE ZHU 2023년 3월 28일
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
JIAN-HONG YE ZHU
JIAN-HONG YE ZHU 2023년 3월 28일
Thank you very much for your insight, it was a great explanation.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

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

카테고리

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