Squeezing a two-dimensional array into a one-dimensional array without using a FOR loop

Hi,
I would like to be able to squeeze a two-dimensional array into a one-dimensional array. Basically, I would like to be able to "erase" the rows of a two-dimensional array. Is there a straight forward way to do this?
As a simple example, suppose that I have an two-dimensional array A:
A=[1 2 3 4; 5 6 7 8; 9 10 11 12];
I would like to have a function that will produce the following one-dimensional array B:
B=[1 2 3 4 5 6 7 8 9 10 11 12];
I can do the following:
A=[1 2 3 4; 5 6 7 8; 9 10 11 12];
B=zeros(1,size(A,1)*size(A,2));
k=1;
for i=1:size(A,1)
for j=1:size(A,2)
B(k)=A(i,j);
k=k+1;
end
end
which I think is a correct algorithm. But, is there a better way to do this, perhaps without using a FOR loop?
Thank you very much for your time.
Andrew DeYoung
Carnegie Mellon University

 採用された回答

Paulo Silva
Paulo Silva 2011 年 6 月 29 日
doc reshape
A=[1 2 3 4; 5 6 7 8; 9 10 11 12]
reshape(A',1,numel(A))

その他の回答 (1 件)

Viraj
Viraj 2023 年 2 月 23 日

0 投票

A=[1 2 3 4; 5 6 7 8; 9 10 11 12];
B=zeros(1,size(A,1)*size(A,2));
k=1;
for i=1:size(A,1)
for j=1:size(A,2)
B(k)=A(i,j);
k=k+1;
end
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

質問済み:

2011 年 6 月 29 日

回答済み:

2023 年 2 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by