How can I create a new matrix with x and y coordinates using a for loop?

1 回表示 (過去 30 日間)
Sebastian
Sebastian 2014 年 1 月 18 日
編集済み: Paul 2014 年 1 月 18 日
Lets say I have a matrix A like this:
A=
0 0 1 0 0 0
0 0 0 0 1 0
0 1 0 0 0 1
I want to create a for loop in which this loop creates a new matrix like this
B=
1 3 1
2 5 2
3 2 3
4 6 3
The first column will be the ones showed in the matrix A(point 1,2,3,4) and the second and third columns will be the x and y coordinates of those points(point 1 is at 3 in the x direction and 1 in the y direction). Is it possible?

採用された回答

Paul
Paul 2014 年 1 月 18 日
編集済み: Paul 2014 年 1 月 18 日
[y,x]=find(A==1);
num=length(x);
B=[(1:num)',x,y];
If you want to sort the points the way you described do for example this:
[y,x]=find(A==1);
num=length(x);
xy=sortrows([x,y],2)
B=[(1:num)',xy]
  3 件のコメント
Paul
Paul 2014 年 1 月 18 日
編集済み: Paul 2014 年 1 月 18 日
Yes but why, this is easier. You can do it like this:
p=1;
[row,col] = size(A);
for i = 1:row
for j=1:col
if(A(i,j)==1)
B(p,:)=[p,j,i];
p=p+1;
end
end
end
Sebastian
Sebastian 2014 年 1 月 18 日
This works perfect for me, Thank you Paul!

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

その他の回答 (0 件)

カテゴリ

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