for loop for variables
77 views (last 30 days)
Show older comments
I have written one code as follows,
for i=1:10
Ai=i;
fprintf('A is: %d \n',Ai)
end
what i want to achieve from here is, I want to store 1,2,3..10 in variables A1,A2,A3...A10. But the code i have created is giving me Ai as variable instead A1,A2...etc and storing Ai=10 at the end.(It has also created row vector A=[1:10])
1 Comment
Stephen23
on 9 May 2016
@Nachiket Patki: just for your future knowledge (because obviously today it is no use telling you this): you picked the worst solution.
Oh well, caecus caeco dux.
Accepted Answer
Weird Rando
on 9 May 2016
@Stephen: Haha I read the same thing somewhere online. But that didn't stop me :3
for i=1:10
eval(sprintf('A%i = i',i))
end
3 Comments
Weird Rando
on 10 May 2016
It been three years, and yeah that did happen. Can't even understand what I code.
More Answers (2)
Azzi Abdelmalek
on 9 May 2016
Edited: Azzi Abdelmalek
on 9 May 2016
It's not a good idea to create variables A1,A2, ..., An. The array A=1:10 contains all your data. Why to create 10 variables, when one variable is sufficient
2 Comments
Stephen23
on 9 May 2016
Yep, and we just told you that doing this is a really bad idea.
It is simple: accessing lots of variables is slow, buggy, and an awful way to write code. Read our answers.
Stephen23
on 9 May 2016
Edited: Stephen23
on 30 Apr 2019
Ugh... this is a really bad idea!
Avoid creating dynamically named variables in MATLAB. This is poor practice as has been explained many times on this forum, and is not recommended by TMW/MATLAB themselves:
EDIT see also:
2 Comments
Stephen23
on 9 May 2016
"what I want to do is I want to store images in different variables"
Well, that's a really bad idea.
"So can you give me some how to do it?"
As I explained in my answer, you should store your images either in:
- an ND numeric array, or
- a cell array.
and use indexing to access them. That's it.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!