MATLAB: Changing of matrixes in for loop

for loop

Hello,
I'd like to change the matrices in a loop rather then using the same formula 8 times. How does this work in a for loop? As you can see in the picture I have Matrices M1 to M8. I'd like to change these in the forloop by filling in Mk. As you can see this creates an error.
Thanks in advance for your support!

Best Answer

Do not number matrices as you've done. It leads to all sort of problems including the one you're facing. Instead store these matrices in an array of matrices (cell array), that you can then simply index.
For now, you can create that array of matrices from all these numbered matrices, but better would be to create the array at the start and never create these numbered variables.
M = {M1; M2; M3; ...};
S = {S_1_1, S_1_2, S_1_3, S_1_4;
S_2_1, S_2_2, ...;
...
};
And suddenly all these loops become extremely easy. For example, your last two loops:
X = cell(size(M)); %predeclare array of matrices for faster code

for k = 1:numel(m)
X{k} = zeros(size(M{k}, 1), 1); %predeclare matrix for faster code
for n = 1:size(M{k}, 1)
X{k}(n) = M{k}(n, 4)*exp(1i*M{k}(n, 5)) + M{k}(n, 6)*exp(1i*M{k}(n, 7));
end
end
F = cell(size(M));
for k = 1:numel(M)
F{k} = sum(S{k, :}) .* X{k}
end
Next, also learn to avoid loops when they're not needed. A faster way to calculate your X would be:
X = cell(size(M)); %predeclare array of matrices for faster code
for k = 1:numel(m)
X{k} = M{k}(:, 4).*exp(1i*M{k}(:, 5) + M{k}(:, 6).*exp(1i*M{k}(;, 7); %operate on all the rows at once
end