How to index all columns but one in a matrix?

Hi!
I want to do index/use all columns in a matrix but a single one, so for example:
A=[1 2 3 4; 1 2 3 4; 1 2 3 4] and I 'd like to get at B=[1 2 4; 1 2 4; 1 2 4].
A long way to that would be: B=[A(:,1:2),A(:,4)], but is there anything faster/built in?
Best Peter

 Risposta accettata

B = A;
B(:,3) = [];

7 Commenti

Thanks! But I'd like to do it without creating a new matrix, so I can use immediately. Like : C=exp([A(:,1:2),A(:,4)]);
James Tursa
James Tursa il 2 Ago 2013
Modificato: James Tursa il 2 Ago 2013
You either need to create a new matrix like I have shown, or you need to explicitly form the new temporary matrix on the fly like you have shown. There is different syntax you can use (including others I have not shown), but they all need to form a new matrix. Some methods may have a slight performance advantage compared to other methods if the matrix involved is large. What is your goal? Why do you prefer one syntax over another? Are you just after a speed improvement or what?
@Peter: "B = A" does not duplicate the matrix. Only a shared data copy is created, while the actual data are used for both variables. In the next line "B(:, 3)=[]" the data are partially duplicated. In consequence, I assume that James' solution is exactly as efficient as Andrei's, because internally exactly the same thing is performed.
@Jan&James: I'm mostly after a speed improvement, while a shorter syntax would be preferable. Given that both are the same regarding the first metric, I'd go for Andrei's solution, as it provides a shorter code. Thanks guys!
why does X([1 1 0 1]) not work?
Because [1 1 0 1] is not a logical vector and you are not accounting for both dimensions. E.g., compare your code to this:
X(:,logical([1 1 0 1]))

Accedi per commentare.

Più risposte (1)

% no need of a new matrix, remake the old one:
A = exp(A(:,[1:2,4]));

Community Treasure Hunt

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

Start Hunting!

Translated by