how rearrange data in a matrix?

1 回表示 (過去 30 日間)
Ved
Ved 2013 年 10 月 19 日
コメント済み: Andrei Bobrov 2013 年 10 月 20 日
I have a data as:
data=[1 2 3 4 5 6 7 8];
I need a new data matrix (4 x 8),like this:
new_data =[ 1 2 0 0 0 0 0 0
0 0 3 4 0 0 0 0
0 0 0 0 5 6 0 0
0 0 0 0 0 0 7 8 ]
How to do it using a FOR loop ? Any help?

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 10 月 19 日
編集済み: Azzi Abdelmalek 2013 年 10 月 19 日
data=[1 2 3 4 5 6 7 8];
n=numel(data);
R=zeros(n/2,n);
R(:,1:2)=reshape(data,2,[])';
out=cell2mat(arrayfun(@(x) circshift(R(x+1,:),[ 0 2*x]),(0:3)','un',0))
%or
data=[1 2 3 4 5 6 7 8];
n=numel(data);
out=zeros(n/2,n);
out(sub2ind(size(out),repmat((1:n/2),2,1),reshape(1:n,2,[])))=data
%or
EDIT
n=numel(data);
a=[reshape(data,2,[]) ;zeros(n,n/2)];
a=a(:);
a(end-n+1:end)=[];
out=reshape(a,n,n/2)'
  2 件のコメント
Ved
Ved 2013 年 10 月 19 日
@Azzi: First two scripts worked perfectly.Thank you !
Ved
Ved 2013 年 10 月 19 日
@Azzi:
Could you please explain the line which is using cell2mat() in your first code.

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2013 年 10 月 19 日
編集済み: Andrei Bobrov 2013 年 10 月 20 日
a = num2cell(reshape(data,1,2,[]),[1 2])
out = blkdiag(a{:});
or
out = kron(eye(4),[1 1])*diag(data);
or
out = reshape(permute(repmat(eye(4),[1,1,2]),[1 3 2]),4,[])*diag(data);
  2 件のコメント
Ved
Ved 2013 年 10 月 20 日
編集済み: Ved 2013 年 10 月 20 日
@Andrei:
Thank You ! but third one is giving an error:
Error using repmat
Too many input arguments.
nevertheless other two options works perfectly.
Andrei Bobrov
Andrei Bobrov 2013 年 10 月 20 日
corrected

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

カテゴリ

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