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

41 次查看(过去 30 天)
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;

回答(1 个)

Jan
Jan 2022-4-27
编辑:Jan 2022-4-27
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by