Search code examples
arraysmatlabfor-loopsequential

Calling for sequential variables in Matlab loops


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!


Solution

  • 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);