Multiple functions using indexation numbers

Hello,
I've got a problem where i have multiple matrix that have similar names but just changes the number of it. p.e.
A_1=[2 4 4
2 9 1]
A_2=[3 5 1
7 8 9]
A_3= ...
A_4= ...
And then i have a function that sums each line and then keeps the result.
A_1_result=[ 10
12]
A_2_result=[ 9
24]
A_3_result=...
A_4_result= ...
I'do this using 1 for cicle similar to this:
for i=1:2
A_1_result(i)=sum(A_1(i,:);
A_2_result(i)=sum(A_2(i,:);
A_3_result ....
end
Isn't there any possibility to put this in a for loop from 1 to 4 and use p.e.
A_{j}_result(i)=sum(A_{j}(i,:);
Thanks in advance

 Réponse acceptée

Sean de Wolski
Sean de Wolski le 3 Jan 2013

2 votes

3 commentaires

Before i've made my question i've read the FAQ. Although i cannot make the desired code. I've tried using it and i'm able to do simple task like:
for i=1:3
eval(sprintf('A_%d_result = [1+2]', i));
end
The thing is that i cannot access to the matrix i want to sum inside the eval. Can u give me an example code for this case plz?
Sean de Wolski
Sean de Wolski le 3 Jan 2013
No, I refuse to use evil eval().
Use a 1x20 cell array as the FAQ suggests. It will make your life much easier.
Jan
Jan le 3 Jan 2013
I agree with Sean's suggestion. The FAQ is called FAQ, because these problems occur frequently. And in all cases avoiding EVAL is the best solution.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 3 Jan 2013

0 votes

I would say that, if you could even do it, for only 4 variables the illegibility it would add to your code would make it not worth it. Right now it's intuitive and easy to follow - why mess it up? You wouldn't even be reducing that many lines of code.

1 commentaire

André Pacheco
André Pacheco le 3 Jan 2013
I just showed a simple case. In my case i have a much more complicated problem where i do have more than 4 variables (around 20) and with much more equations than a simple sum. It would save me from writing down all the variables and i wanted to put the option that u could chose the number of variables. And thats not possible if i have to write down all the options for only 1 variable, to 20 variables. It would be necessary a 20 if's for the different number of variables u could chose.

Connectez-vous pour commenter.

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by