What command will erase all but the first three columns of a matrix in MATLAB?
I am essentially trying to take a开发者_JAVA技巧 matrix, a
, and turn it into a matrix af which has the values in the first three columns of a
. I just want to prune a
down to only its first three columns.
newMatrix = oldMatrix(:,1:3)
This says "I have a matrix called oldMatrix. I want to store a subset of that matrix into newMatrix" and the dimensions in the parentheses say what subset you want. The first colon signifies "all rows" and the 1:3 signifies "columns 1 through 3".
a = ones(10,10);
a = a(:,1:3);
If you wish to erase all but the first three columns, then do this...
A(:,4:end) = [];
If you wish to copy over only the first three columns into a new array, then this is right...
B = A(:,1:3);
Of course, you can always do this to essentially erase those last columns...
A = A(:,1:3);
Is one better than the other? There would seem to be little difference.
A = rand(4000);
tic,A(:,4:end) = [];toc
Elapsed time is 0.044124 seconds.
A = rand(4000);
tic,A = A(:,1:3);toc
Elapsed time is 0.040166 seconds.
There seems to be a small (repeatable) difference, but I'd not totally trust that to be consistent. The next release of MATLAB might change those times.
精彩评论