フィルターのクリア

Save New Variable to the Workspace for every iteration with a 'for' cycle

1 回表示 (過去 30 日間)
kerozi
kerozi 2016 年 5 月 23 日
コメント済み: kerozi 2016 年 5 月 24 日
Hello all,
I've been trying to save the Q_bar(3x3 matrix) answer seperately for every theta input but I am failing to save the Q_bar answer for each iteration. Because the only output is the final Q_bar matrix.
for theta = [0,45,60,45,45,60,45,0];
m = cos(theta*pi/180);
n = sin(theta*pi/180);
T = [m.^2 n.^2 2*m*n ; n.^2 m.^2 -2*m*n ; -m*n m*n m.^2-n.^2];
Tinv = inv(T);
Q_bar = Tinv*Q*T;
Q_bar = Q_bar(theta);
end
The final output should be Q_bar(0) = [3x3 matrix] , Q_bar(45) = [3x3 matrix], Q_bar(60) = [3x3 matrix] etc.
What can I do?
Thank You already
  3 件のコメント
kerozi
kerozi 2016 年 5 月 23 日
I have thought with another for loop inside should give an answer but it does not.
theta = [0,45,60,45,45,60,45,0];
for i=1:8;
m = cos(theta(i)*pi/180);
n = sin(theta(i)*pi/180);
T = [m.^2 n.^2 2*m*n ; n.^2 m.^2 -2*m*n ; -m*n m*n m.^2-n.^2];
Tinv = inv(T);
Q_bar = Tinv*Q*T;
Q_bar = Q_bar(theta(i));
end
AND I FORGOT TO TELL THAT Q MATRIX IS ALSO 3x3 MATRIX.
Stephen23
Stephen23 2016 年 5 月 23 日
Don't try to create variables in a loop. This is slow, buggy, and not robust. Read this to know why:

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2016 年 5 月 23 日
編集済み: Stephen23 2016 年 5 月 23 日
Exactly as Adam said in their comment, just use a 3D array like this:
Q = randi(9,3,3);
vec = [0,45,60,45,45,60,45,0];
out = NaN([size(Q),numel(vec)]);
for k = 1:numel(vec)
theta = vec(k);
m = cos(theta*pi/180);
n = sin(theta*pi/180);
T = [m.^2 n.^2 2*m*n ; n.^2 m.^2 -2*m*n ; -m*n m*n m.^2-n.^2];
Tinv = inv(T);
Q_bar = Tinv*Q*T;
out(:,:,k) = Q_bar;
%Q_bar = Q_bar(theta);
end
But note that you should use \ instead of inv.
  1 件のコメント
kerozi
kerozi 2016 年 5 月 24 日
Thank You, as much as it seems an easy task, it was hard for me to comprehend the overall. But you made it happen. Thank You so much.

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2016 年 5 月 23 日
You're trying to create variables like Q_bar0, Q_bar45. etc.? DON'T DO THAT. That would make your code more difficult to read and probably slower. Read this Answer for an explanation.
Adam's suggestion is the recommended approach.
theta = 0:45:360;
M = zeros(3, 3, length(theta));
for k = 1:length(theta)
T = theta(k);
M(:, :, k) = [1 0 0; 0 cosd(T) -sind(T); 0 sind(T) cosd(T)];
end
The rotation matrix for the angle theta(N) [for N between 1 and length(theta)] is M(:, :, N).
And don't use inv, use the backslash operator \ instead.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by