For loop help for Linear Algebra Class

I cant seem to get this algorithm code correct.
%HW3 #2
% Given:
%
% y_k denotes k index
%
% y_k=A*x_k
% r_k=norm(y_k) / norm(x_k)
% x_(k+1) = y_k / norm(y)
%
% Create a vector with 0-50 indexes of k
clear all;
close all;
A = [-5,3,-1;0,4,1;0,0,-2];
x(1)=[1;1;1];
for k = 1:51
y{k} = A.*x;
r{k} = norm(y)/norm(x);
x{k+1} = y/norm(y);
end
I receive the error: "In an assignment A(I) = B, the number of elements in B and I must bethe same."
Im not sure how to go about fixing the problem, because I do not fully understand how mat lab operates yet.

4 件のコメント

Cedric
Cedric 2013 年 2 月 1 日
In addition to Walter's answer, y in your loop is the full cell array. It is probably not what you want to use when you compute x{k+1}.
Sean Murphy
Sean Murphy 2013 年 2 月 1 日
It seemed that I had to define each variable with the cell array index in order to obtain no errors.
Sean Murphy
Sean Murphy 2013 年 2 月 1 日
編集済み: Sean Murphy 2013 年 2 月 1 日
Thanks guys!!
Fixed code:
%HW3 #2
% y_k=A*x_k
% r_k=||y_k||_2 / ||x_k||_2
% x_k+1 = y_k / ||y_k||_2
% r = norm(y0,2)/norm(x0,2)
% x_k1 = y0/norm(y0,2)
clear all;
close all;
A = [-5,3,-1;0,4,1;0,0,-2];
x{1}= [1;1;1];
for k = 1:51
y{k} = A*x{k};
r{k} = norm(y{k})/norm(x{k});
x{k+1} = y{k}/norm(y{k});
end
q_x = [x{1,51}]
q_y = [y{1,51}]
q_r = [r{1,51}]
save x50.dat q_x -ascii
save y50.dat q_y -ascii
save r50.dat q_r -ascii
Cedric
Cedric 2013 年 2 月 1 日
編集済み: Cedric 2013 年 2 月 1 日
You're most welcome! Note that x, y, r are 1D cell arrays, so x{1,51} is the same as x{51}, and the [ ] that you use in [x{1,51}] have no effect.
If you wanted to save all the x vectors though, you could concatenate all cells content of x (which is a cell array, so its elements are cells whose content are 3x1 numeric arrays) the following way: [x{:}], which would be a 3x52 array of vectors in column. This dimension should also make you realize that as you compute x{k+1}, the boundaries that you are defining might need some additional thoughts, especially if you wanted to use then simultaneously x and y (as [y{:}] is a 3x51 array)..

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

 採用された回答

Walter Roberson
Walter Roberson 2013 年 2 月 1 日

0 投票

Instead of
x(1)=[1;1;1];
you would need
x{1}=[1;1;1];
to avoid that error.
However, then when you go to the A.*x you would fail in trying to multiply A by a cell array. Try
y{k} = A.*x{k}

2 件のコメント

Cedric
Cedric 2013 年 2 月 1 日
y{k} = A*x{k}
Walter Roberson
Walter Roberson 2013 年 2 月 1 日
True, it would be matrix multiplication desired in that case.
Note that your r{k} and x{k+1} assignments will need similar adjustments to use x{k} and y{k}

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by