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

41 views (last 30 days)
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;

Answers (1)

Jan
Jan on 27 Apr 2022
Edited: Jan on 27 Apr 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!