Move selected column from a matrix to another

3 views (last 30 days)
Hello Matlab community,
I am a beginner in Matlab.
I have a matrix M, I would like to select from this matrix the columns which have a value between Xmin and Xmax in the lign 310 and also value between Ymin and Ymax in the lign 620. Then copied the columns selected in a new matrix. Below, it's the code I tried, however the answer is that all the colums are copied into the matrix x.
Xmin = 429500;
Xmax = 431500;
Ymin = 5907000;
Ymax = 5910000;
n = 7000;
dt = 620;
x = zeros(dt,n);
y = zeros(dt,n);
for in=1:n
if Xmin>= M(310,in)<= Xmax & Ymin>=M(620,in)<= Ymax;
x(:,in) = M(:,in);
else
x(:,in) = x(:,in);
end
end
Can someone help me please?
Regards
Jonathan

Accepted Answer

Stephen23
Stephen23 on 13 Sep 2019
Edited: Stephen23 on 13 Sep 2019
Replace the loop with this:
idx = M(310,:)>=Xmin & M(310,:)<=Xmax & M(620,:)>=Ymin & M(620,:)<=Ymax;
x(:,idx) = M(:,idx);
Note that the syntax you invented A>=X<=B is valid but does not do what many beginners think it does: it is actually equivalent to (A>=X)<=B, which is unlikely to be very useful for you. The reason is that all MATLAB logical comparisons are bivariate functions, not trivariate functions (or arbitrarily chainable N-variate functions), as their documentation clearly describes.
Note that even if the logical operators were trivariate functions (which they aren't), your logic is anyway incorrect: it would have to be Xmin<=M(310,in)<=Xmax
The correct syntax for what you want is as two comparisons with a logical and, e.g.: X>=A & X<=B.
  2 Comments
Stephen23
Stephen23 on 15 Sep 2019
Jonathan Demmer's "Answer" moved here:
Hi Stephen,
Thank you very much it works well.
Can i ask one more question: The matrix created has coloumns with 0 in it. I would like to delete the columns with zeros and keep only the columns with the results. Do you know how can I do that?
Cheers
Jonathan
Stephen23
Stephen23 on 15 Sep 2019
"I would like to delete the columns with zeros and keep only the columns with the results"
That really depends on where the zeros are coming from. If they are an artefect of the indexing then possibly you just need to not use indexing on the results array:
out = M(:,idx);
If the zeros are in the data (independently of the indexing you asked about in this thread) then you can detect them and use indexing to remove those columns.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!