Why can't the index variable of a for loop be stored in a structure or other array?

4 Ansichten (letzte 30 Tage)
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)

Antworten (3)

Stephen23
Stephen23 am 23 Mär. 2023
Verschoben: Matt J am 23 Mär. 2023
"More broadly, is there some way to store index variables together?"
status.loop1 = 1:10;
for k = status.loop1
%do something
end
  1 Kommentar
Daw-An Wu
Daw-An Wu am 23 Mär. 2023
Hi, I am looking to have "k" bundled up in a structure, or something else. In code with a lot of loops, this avoids a mess of variables in the workspace, and makes it more convenient to pass all those states into a function, or to check how far each loop has gotten - after an error etc.

Melden Sie sich an, um zu kommentieren.


Fangjun Jiang
Fangjun Jiang am 23 Mär. 2023
Bearbeitet: Fangjun Jiang am 23 Mär. 2023
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
0 1 -1
  3 Kommentare
Steven Lord
Steven Lord am 24 Mär. 2023
status = struct('index', {1, 2, 3})
status = 1×3 struct array with fields:
index
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
ans = 1
ans = 2
ans = 3
I get three outputs from this comma-separated list.

Melden Sie sich an, um zu kommentieren.


John D'Errico
John D'Errico am 23 Mär. 2023
Surely this is not a big problem?
for ind = 1:10
status.ind = ind;
% do Stuff
end
  2 Kommentare

Melden Sie sich an, um zu kommentieren.

Kategorien

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by