How can I use "for loop" for this script?
1 回表示 (過去 30 日間)
古いコメントを表示
Hi, I have a random matrix with large dimension and I have to form augmented matrix. My script for given dimensions is good but for random and large matrices I need a "for loop". For example:
X = rand(3,5);
[n,m]=size(X);
A0=X(:,m);
A1=[X(:,m-1); A0];
A2=[X(:,m-2); A1];
A3=[X(:,m-3); A2];
A4=[X(:,m-4); A3];
Now, A4 gives the first column of augmented matrix. The other columns can be calculated in the same way. But I need a loop to calculate all the columns regardless of the dimension of X. Assume that X is 3*100. How can I calculate the augmented matrix?
0 件のコメント
採用された回答
Mohammad Abouali
2015 年 12 月 8 日
編集済み: Mohammad Abouali
2015 年 12 月 8 日
Looking at your code:
A0=X(:,m);
A1=[X(:,m-1); A0];
A2=[X(:,m-2); A1];
A3=[X(:,m-3); A2];
A4=[X(:,m-4); A3];
A0 is the last column of X, A1 is the last two column of X (in one long vector), A2 is the last three column of X (shown in one long vector) and so on.
if you just want the last A, i.e. A4 or in case if X is (3x100) then A99 then all you need to do is:
A4 = X(:); % or reshape(X,[],1);
or
A99 = X(:) % or reshape(X,[],1);
otherwise, you could write a function like this:
function AN=getAN(X,n)
if (n<0 || n>(size(X,2)-1))
error('wrong n');
end
AN=reshape(X(:,end-n:end),[],1);
end
so now if you want A0
A0=getAN(X,0);
or if you want A4 do
A4=getAN(X,4);
you can do this in a loop as follow:
for n=0:4
A{n+1}=getAN(X,n);
end
NOTE: it is not a good idea to name your variabl A0, A1, ... Try to use cell, tables, arrays, and other structures.
0 件のコメント
その他の回答 (1 件)
mili ss
2015 年 12 月 8 日
1 件のコメント
Mohammad Abouali
2015 年 12 月 8 日
編集済み: Mohammad Abouali
2015 年 12 月 8 日
The definition of XD seems to be different than what you explained.
X(:) gives only the step 1, which was based on your code.
Based on the XD definition in 02.jpg here how you can do it:
XD=[ reshape(X(:,1:end-2),[],1), ...
reshape(X(:,2:end-1),[],1), ...
reshape(X(:,3:end),[],1)]
Here is an example:
X=reshape(1:15,3,5)
X =
1 4 7 10 13
2 5 8 11 14
3 6 9 12 15
XD=[ reshape(X(:,1:end-2),[],1), ...
reshape(X(:,2:end-1),[],1), ...
reshape(X(:,3:end),[],1)]
XD =
1 4 7
2 5 8
3 6 9
4 7 10
5 8 11
6 9 12
7 10 13
8 11 14
9 12 15
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!