I am trying to make a new matrix for each iteration of a for loop

41 visualizaciones (últimos 30 días)
Kiernan O'Boyle
Kiernan O'Boyle el 27 de Abr. de 2022
Comentada: Stephen23 el 27 de Abr. de 2022
I am not sure how to make a new matrix for each iteration, I would like to have Q_bar1, Q_bar2, Q_bar3, Q_bar4 each having differnt values. I know I need to initalize if I am using Q_bar(i) but I am not sure how to do that.
%% Making Qbar matrices for all thetas
for i = 1:length(theta)
m = cosd(theta(i));
n = sind(theta(i));
T1 = [m^2, n^2, 2*n*m
n^2, m^2, -2*n*m
-n*m, n*m, (m^2)-(n^2)];
T2 = [m^2, n^2, n*m
n^2, m^2, -n*m
-2*n*m, 2*n*m, (m^2)-(n^2)];
Q_bar(i)= inv(T1)*Q*T2;
end
ERROR MESSAGE:
Unable to perform assignment because the indices on the left side are not compatible with the
size of the right side.
Error in project2 (line 85)
Q_bar(i)= inv(T1)*Q*T2;

Respuestas (1)

Jan
Jan el 27 de Abr. de 2022
Editada: Jan el 27 de Abr. de 2022
Q_bar = cell(1, length(theta));
for i = 1:length(theta)
m = cosd(theta(i));
n = sind(theta(i));
T1 = [m^2, n^2, 2*n*m; ...
n^2, m^2, -2*n*m; ...
-n*m, n*m, m^2 - n^2];
T2 = [m^2, n^2, n*m; ...
n^2, m^2, -n*m: ...
-2*n*m, 2*n*m, m^2 - n^2];
Q_bar{i} = inv(T1) * Q * T2;
end
Or alterntively:
Q_bar = zeros(3, 3, length(theta));
for i = 1:length(theta)
m = cosd(theta(i));
n = sind(theta(i));
T1 = [m^2, n^2, 2*n*m; ...
n^2, m^2, -2*n*m; ...
-n*m, n*m, m^2 - n^2];
T2 = [m^2, n^2, n*m; ...
n^2, m^2, -n*m: ...
-2*n*m, 2*n*m, m^2 - n^2];
Q_bar(:, :, i) = inv(T1) * Q * T2;
end
Note, that T1 \ Q * T2 is numerically more stable than calculating the inverse explicitely.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by