Determining Quadrants in a Matrix

3 ビュー (過去 30 日間)
TS
TS 2015 年 5 月 4 日
コメント済み: Yong Cho 2019 年 10 月 1 日
matrix=load('Data');
x=matrix(:,1);
y=matrix(:,2);
if x>0 & y>0
matrix(:,3)=1
elseif x<0 & y>0
matrix(:,3)=2
elseif x<0 & y<0
matrix(:,3)=3
elseif x>0 & y<0
matrix(:,3)=4
elseif x<-128 & y<-128 & x>128 & y>128
'Invalid Values'
end
With this code, I'm trying to put separate points into a matrix. However, my code doesn't do anything with the values as far as I have seen. I was trying to put the quadrant values into a third column so that I could code the script to count all points in each quadrant, so there is a reason for it. If you have any suggestions I would greatly appreciate it.

採用された回答

Jan
Jan 2015 年 5 月 4 日
The if command evaluates the condition as a scalar. This is logical, because what could this mean:
if [true, false]
? Is this true or not? Therefore Matlab inserts a all() in the condition, if the user forgot this. So you have:
if all(x>0 & y>0)
And this is never true. What you want is:
index = (x>0 & y>0);
matrix(index, 3) = 1;
...
The last condition is magic:
elseif x<-128 & y<-128 & x>128 & y>128
You are looking for numbers which are smaller than -128 and larger than 128? You want an or.
  1 件のコメント
TS
TS 2015 年 5 月 4 日
編集済み: TS 2015 年 5 月 4 日
Thank you!

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

その他の回答 (1 件)

Stephen23
Stephen23 2015 年 5 月 4 日
編集済み: Stephen23 2015 年 5 月 4 日
Actually you do not need these if statements at all: just use logical indexing directly, like this:
matrix = load('Data');
x = matrix(:,1);
y = matrix(:,2);
matrix(x>0 & y>0,3) = 1;
matrix(x<0 & y>0,3) = 2;
matrix(x<0 & y<0,3) = 3;
matrix(x>0 & y<0,3) = 4;
  1 件のコメント
Yong Cho
Yong Cho 2019 年 10 月 1 日
This is ausome answer I ever read!

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

カテゴリ

Help Center および File ExchangeParticle & Nuclear Physics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by