Why can't the index variable of a for loop be stored in a structure or other array?
9 ビュー (過去 30 日間)
古いコメントを表示
status.loop1 = 0;
for status.loop1 = 1:10
%do something
end
returns the error "Invalid use of operator." pointing to the dot.
Similarly,
status = [0 0 0];
for status(1) = 1:10
%do something
end
returns "Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters."
Same for cell array.
Why?
More broadly, is there some way to store index variables together? (to keep workspace neat, have access to all status variables in one place, etc)
0 件のコメント
回答 (3 件)
Fangjun Jiang
2023 年 3 月 23 日
編集済み: Fangjun Jiang
2023 年 3 月 23 日
There is no mention of any requirement on the name of the index varialbe, here in the document for "for",
My explaination is this:
for index = values
statements
end
"index" needs to be a valid variable name, but "status.loop1" or "status(1)" is not a valid variable name.
You could do things like this:
status=[ 0 1 -1];
for k=status
disp(k);
end
3 件のコメント
Fangjun Jiang
2023 年 3 月 24 日
- It might be a matter of preference. Inside the loop, likely you will need to reference the index variable many times, do you prefer MyData(index), or MyData(mystruct.status.loop1), or MyData(status(1))?
- It might be a matter of necessity. status=[0 0 0] can be stored and used as the values to go through the loop, but you still need a "counter" or "pointer" to know what is the current loop thus the next loop. Otherwise, how do you know when to finish the loop or which "0" in status=[0 0 0] are you looping at now? The index variable "k" only has one element, not the copy of status=[0 0 0].
Steven Lord
2023 年 3 月 24 日
status = struct('index', {1, 2, 3})
If that syntax worked, what would you expect this code segment to do? What would the variable status be after it executed? Be specific.
% for status.loop = 4:6
% disp(sum([status.loop])
% end
Note that if I write the expression:
status.index
I get three outputs from this comma-separated list.
John D'Errico
2023 年 3 月 23 日
Surely this is not a big problem?
for ind = 1:10
status.ind = ind;
% do Stuff
end
2 件のコメント
Stephen23
2023 年 3 月 26 日
"The main question is still why this is necessary at all."
Because there are many cases to consider, e.g. non-scalar structures:
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!