Loop with different outcome name

1 Ansicht (letzte 30 Tage)
Yeeun Son
Yeeun Son am 19 Okt. 2020
Kommentiert: Stephen23 am 19 Okt. 2020
Hi,
I'm trying to create a loop that gives me outcomes with different names
For example,
for x=1:3
y=x+2
end
This code gives me y=3, y=4, y=5
But I want to change my code so that it gives me something like
y1=3, y2=4, y3=5
so that I would be able to know which y corresponds to which x values later.
Is there anyway to acheive this?
Many thanks in advance!
  1 Kommentar
Stephen23
Stephen23 am 19 Okt. 2020
"But I want to change my code so that it gives me something like y1=3, y2=4, y3=5"
That would be about the worst approach to storing data. Read this to know why:
The simple, neat, and very efficient MATLAB approach is to use indexing. You should use indexing too.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 19 Okt. 2020
Bearbeitet: Ameer Hamza am 19 Okt. 2020
Creating variable names like y1, y2, ... is not a good coding practice and highly non-recommended: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. A better approach is to use array
y = zeros(1, 3)
for x = 1:3
y(i) = x+2
end
Then access values using indexing
y(1) % access first element
Also, note that your for-loop can be vectorized
x = 1:3;
y = x+2;

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by