How can I use a for loop to reassign matrix names?
29 views (last 30 days)
Show older comments
Hi there! I am trying to write a 'for' loop which does the following:
for i = 1:9
a = a0i; b = b0i; cx = c0i(:, 1); cy = c0i(:, 2); t = t00i;
foneplotp(a, b, cx, cy, t, period)
end
I have matrices labeled a01, a02, a03, etc. in my workspace, but when I try to run this, I get the error:
Undefined function or variable 'a0i'.
Is there a way to do this with a 'for' loop in MATLAB?
Thanks!
Miranda
0 Comments
Accepted Answer
Star Strider
on 7 May 2014
It’s horrible programming style, but it’s possible. So long as your matrices already exist and you simply need to call them, here is an example of what you can do:
a01 = pi;
c01 = [5 7];
for i = 1:9
a = eval(sprintf('a0%d',i))
cx = eval(sprintf('c0%d(:, 1)',i))
end
I used a01 and c01 to test the code, so remove those in your actual code. I listed them here so you can test them to see how it works.
2 Comments
Star Strider
on 7 May 2014
Edited: Star Strider
on 7 May 2014
My pleasure!
The sincerest expression of appreciation here on MATLAB Answers is to accept the answer that solves your problem. It also helps others with similar questions find them.
More Answers (1)
Image Analyst
on 7 May 2014
Why complicate it? Just do
foneplotp(a01, b01, c01(:,1), c01(:,2), t001, period);
foneplotp(a02, b02, c02(:,1), c02(:,2), t002, period);
foneplotp(a03, b03, c03(:,1), c03(:,2), t003, period);
foneplotp(a04, b04, c04(:,1), c04(:,2), t004, period);
foneplotp(a05, b05, c05(:,1), c05(:,2), t005, period);
foneplotp(a06, b06, c06(:,1), c06(:,2), t006, period);
foneplotp(a07, b07, c07(:,1), c07(:,2), t007, period);
foneplotp(a08, b08, c08(:,1), c08(:,2), t008, period);
foneplotp(a09, b09, c09(:,1), c09(:,2), t009, period);
It's only 9 lines long and a heck of a lot simpler to understand and maintain than the crazy workaround mentioned in the FAQ
3 Comments
Image Analyst
on 7 May 2014
Edited: Image Analyst
on 7 May 2014
You should NOT have 100 differently named variables! How did you ever create those in the first place? Did you use the method that the FAQ shows you but advises against ? Well you can do the same thing to get those names and assign them to other variables like a,b,c, etc.
You should use a 2D array instead of different names. This is what the FAQ strongly recommends . Please don't do what you are asking.
See Also
Categories
Find more on Logical 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!