0

I have just started programming in Matlab, so I might be asking a very simple question.

Let's say I have 10 variables named: X_1, X_2 … X_10. Each of these variables is a 3x3 matrix.

I want to multiply the individual matrices in a 'for loop' by a constant and store them in the variables Y_1, Y_2 … Y_10. The latter would not be a problem, since I know how to store the new variables sequentially in a cell array (also using a 'for loop').

What I cannot figure out is how to call the X variables in a 'for loop' having j=1:10. I have seen a few answers that use 'eval', but many people say is not the most efficient way.

Could anyone help me?

Many thanks in advance!

aulky11
  • 79
  • 6
  • Can you use cell arrays or the third dimension (called "pages")? – DasKrümelmonster Nov 17 '14 at 19:00
  • 3
    To sort of elaborate on @DasKrümelmonster's comment on the third dimension if I got that right - Instead of creating such 10 variables, why not have a 3D array of size `3 x 3 x 10` to store all of that data in the first place? – Divakar Nov 17 '14 at 19:02
  • Possible duplicate: http://stackoverflow.com/questions/15463411/how-to-call-sequential-variables-with-for-loop-matlab?rq=1 – David K Nov 17 '14 at 20:20

1 Answers1

0

definitely creating a 3D array is the best solution.

Then instead of looping, which is generally slow in MATLAB and other interpreted languages, you can use mtimesx function if you deal with matrix-matrix or -vector multiplication, or just use bsxfun for elementwise multiplication

X(:,:,1) = X_1;
X(:,:,2) = X_2;
%// and so on

constants = permute(1:10, [3,1,2])

Y = bsxfun(@times, X, constants);
Dima Lituiev
  • 12,544
  • 10
  • 41
  • 58
  • Thanks to all of you for the help! While storing the variables in (3D) arrays is useful, it seems from your answers that I would have to do it manually the first time so that I can call them by means of X(:,:,n). What if instead of 10 variables, I have 1000? Is there a way of calling them to store them in the array sequentially? – aulky11 Nov 18 '14 at 22:26
  • from where do you take your data? probably you do not enter them manually. You do not need to enter them into intermediate arrays. Manually you can put them directly. PS: please upvote or accept question ) – Dima Lituiev Nov 18 '14 at 23:00
  • Thanks again! I import my data from different Excel files. I usually read around 10 different input variables, each for 20 years. Each of these variables can be relatively big matrices (e.g. 5000 x 5000). I guess I will have to store them in arrays manually the first time (as you suggest) and then call them by means of loops. Very helpful! – aulky11 Nov 19 '14 at 08:38
  • best if you have csv files (more standard). but anyway, when you read, just assign them into your `X`, e.g. you have a loop through line index `n`, then assign them as `X(:,:, n) = ...`. – Dima Lituiev Nov 19 '14 at 11:24