Matlab index (I tried to name a matrix to use in a loop like variables.)

3 ビュー (過去 30 日間)
Sakunrat Jaejaima
Sakunrat Jaejaima 2015 年 7 月 24 日
コメント済み: Jan 2015 年 7 月 24 日
I tried to name a matrix to use in a loop like variables.
for example
A(1)=[1 2;3 4]
A(2)=A(1)*2
A(3)=A(2)*2
.
.
.
A(j)=A(j-1)*2
But I can't use the notation A(j) in the loop. what should I call the j of A?

回答 (3 件)

bio lim
bio lim 2015 年 7 月 24 日
You can use cell arrays to do the task. Simple example is,
A{1} = [1 2; 3 4];
for j = 2 : 10;
A{j} = A{j-1} * 2;
end
  3 件のコメント
bio lim
bio lim 2015 年 7 月 24 日
編集済み: bio lim 2015 年 7 月 24 日
It is better to use curly braces rather than using normal brackets. For example, if you define a matrix A, then A(i) suggests the i'th element of the A matrix (as a column vector ). Moreover, your code
n=4; % define accord to your requriements
A(1)=[1 2;3 4]
for i=1:n
A(i)=A(i-1)*2;
end
won't work because in A(i) = B, the number of elements in i and B must be the same.
Jan
Jan 2015 年 7 月 24 日
A{j} is the wanted matrix. The curly braces mean, that the contents of the cell array is replied, not the cell itself.

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


Muhammad Usman Saleem
Muhammad Usman Saleem 2015 年 7 月 24 日
編集済み: Muhammad Usman Saleem 2015 年 7 月 24 日
use the for loop approach to save time. Please define n(representing the times you want these calculations
n=4; % define accord to your requriements
A(1)=[1 2;3 4]
for i=1:n
A(i)=A(i-1)*2;
end
  3 件のコメント
Muhammad Usman Saleem
Muhammad Usman Saleem 2015 年 7 月 24 日
@Walter actually the given question required little more explanations. Specially in term of output (vector or matrix)
Walter Roberson
Walter Roberson 2015 年 7 月 24 日
Either way your code A(1) = [1 2; 3 4]; will not work.

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


Jan
Jan 2015 年 7 月 24 日
Either use a cell array, as coffee Murun has suggested:
A{1} = [1 2; 3 4];
for j = 2 : 10;
A{j} = A{j-1} * 2;
end
Or use a 3D-array:
A(:,:,1) = [1 2; 3 4]; % This is the same as: A = [1 2; 3 4]
for j = 2 : 10;
A(:, :, j) = A(:, :, j-1) * 2;
end

カテゴリ

Help Center および 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