Move selected column from a matrix to another

9 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2019-9-13
编辑:Stephen23 2019-9-13
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 个评论
Stephen23
Stephen23 2019-9-15
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 2019-9-15
"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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by