I have a matrix A=[1 2 3; 1 2 9; 2 3 4]. I want a matrix B whose column 1 is equal to 1. How can I do this? B=[1 2 3; 1 2 9]

I have a matrix A=[1 2 3; 1 2 9; 2 3 4]. I want a matrix B whose column 1 is equal to 1. How can I do this? B=[1 2 3; 1 2 9]

 Accepted Answer

B=A(A(:,1)==1,:);
Lookup "logical addressing" in documentation for details on how this works--it's important Matlab syntax.

6 Comments

How about if I want to get B=[1 2 3; 1 2 9; 0 0 0] i.e to get a matrix of same size but with 0 entry for whose column 1 are not equal to 1.
Ah, come on-- think a little. You've seen how to find one set, extrapolating that to the other problem isn't difficult. Let's at least see an attempt (big hint: if you can dispense w/ keeping original A it's also a one-liner, working on the existing content of A; if not, copy A, then go to work).
Why are you comparing A to 1? That was not a specification he gave, at least not explicitly.
Implied interpretation of the request based on the value of A and the desired answer, B. B in his first ? is the two rows from A whose first columns are 1. That that was the correct interpretation would be inferred by his acceptance of the answer. :)
That his specification was indirect and implicit rather than explicit is, as you note, also true. :)
A precise specification never hurts; oftentimes is the crux of much difficulty in endeavoring to answer a query but in this case it was possible to infer what was desired with less than perfect case statement.
That's really tilting at windmills if were to let this level of mis- or incomplete specification stop us in our tracks! (vbg)

Sign in to comment.

More Answers (1)

You say "I have a matrix A=[1 2 3; 1 2 9; 2 3 4]. I want a matrix B whose column 1 is equal to 1. How can I do this? B=[1 2 3; 1 2 9]" You just gave the answer in the question itself! The answer is
B=[1 2 3; 1 2 9];
Read your question. The matrix A is not involved AT ALL in how you came up with B. No criteria or tests were to be applied to A, so A can just be ignored.

Tags

Asked:

on 8 May 2014

Edited:

dpb
on 10 May 2014

Community Treasure Hunt

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

Start Hunting!