MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Italo on 13 Nov 2013

Hello community,

my knowledge of Matlab is limited, I admit it. So, I am sorry if I am going to make mistakes.

I have to create a series of variable using a "for" loop.

I make this:

--------------------------

for i=1:3

eval(['A' num2str(i) '= i'])

end --------------------------

and it works well, it makes 3 variables A1, A2, A3.

But I need to use this variables to make other variables B1, B2, B3 where Bi=Ai*i. So I should have B1=A1*1=1, B2=A2*2=2*2=4, B3=A3*3=3*3=9

I tried something like this:

----------------------------

for i=1:3

eval(['A' num2str(i) '= i']) eval(['B' num2str(i) '= 'A' num2str(i) '*i])

end ------------------------------

but it gives me error and it doesn't work. Of course I simplified things, the real code is a bt more complicated but I need to know the basics of how this could work.

Thank you

*No products are associated with this question.*

Answer by Amit on 22 Jan 2014

Edited by Amit on 22 Jan 2014

Italo, I am glad you're trying out things on matlab.

Matlab is very good with matrixes. What you're doing in these can be done much easily. For example:

A = 1:3; B = A.*A; %

You can find many tutorials online on how to use MAtlab. For example: http://www.mathworks.com/academia/student_center/tutorials/launchpad.html

Amit on 22 Jan 2014

In you code:

for i=1:3 eval(['A' num2str(i) '= i']) eval(['B' num2str(i) '= A' num2str(i) '*i']) % Issue was Here. Notice the positions of ' end

Bruno Pop-Stefanov on 22 Jan 2014

I would like to add that `eval` is #1 in this list: Top 10 MATLAB code practices that make me cry

## 1 Comment

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/105936#comment_191573