フィルターのクリア

Listing elements from one matrix to another

4 ビュー (過去 30 日間)
Enthusiasten
Enthusiasten 2019 年 12 月 10 日
編集済み: Enthusiasten 2019 年 12 月 11 日
Hello all,
I have a 500 by 1500 matrix.
As an example I got A, a 3 by 9 matrix. The elements displayed are coordinates in form of x y z x y z ...
A = [ 0 0 0 2 1 0 0 0 0; 1 2 0 0 0 0 3 2 0; 0 0 0 2 3 1 0 0 0 ];
I want all relevant elements (x/=0) now listed as below. Also, I do not want any row containg only zeros.
B = [2 1 0; 1 2 0; 3 2 0; 2 3 1]
The order is not important. It is just important that these x y z coordinates stick together and every new point gets a new row.
What I got so far is following code.
for i=1:size(A,1)
for j=1:3:size(A,2)-2
if A(i,j)>0
B(:,j)=A(i,j);
B(:,j+1)=A(i,j+1);
B(:,j+2)=A(i,j+2);
else ;
end
end
end
As a result I get following code below.
B = [1 2 0 2 3 1 3 2 0]
I noticed, that this loop is overwriting numbers of prevoius rows in the same column.
Kind Regards

採用された回答

Gatech AE
Gatech AE 2019 年 12 月 10 日
The formatting in the example you gave us did not translate well; however, the best way to do this can avoid for loops entirely. Using the dimensions of the true matrix, where the columns are a multiple of three, we can do the following.
% Create a column vector of all x,y,z values regardless of matrix size
x = reshape(A(:,1:3:end),[],1);
y = reshape(A(:,2:3:end),[],1);
z = reshape(A(:,3:3:end),[],1);
% Clean up cases where x = 0 with logical indexing, and B is the result of concatenation
mask = x~=0;
B = [x(mask) y(mask) z(mask)];
  1 件のコメント
Enthusiasten
Enthusiasten 2019 年 12 月 11 日
編集済み: Enthusiasten 2019 年 12 月 11 日
Thanks four your answer and your explanation. It worked perfectly. I know this was an easy question, but since my brain stuck in for-loops, I forgot to think 'out of the box'.

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

その他の回答 (1 件)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019 年 12 月 10 日
A = [0 0 0 2 1 0 0 0 0; 1 2 0 0 0 0 3 2 0; 0 0 0 2 3 1 0 0 0];
B=reshape(A',3,[])';
B(sum(B,2)==0,:)=[]
  1 件のコメント
Enthusiasten
Enthusiasten 2019 年 12 月 11 日
Thanks four your answer! It worked like 'Gatech AE' answer perfectly.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by