Home > Mobile >  How to remove ith column of a matrix using for loop
How to remove ith column of a matrix using for loop

Time:10-08

Using MatLab, I am attempting to begin with a matrix,

column1 column2 column3 column4 column5
1 4 7 10 11
2 5 8 11 12
3 6 9 12 13

and use a for loop to obtain 5 matrices, one with each of the columns removed, according to:

column2 column3 column4 column5
4 7 10 11
5 8 11 12
6 9 12 13
column1 column3 column4 column5
1 7 10 11
2 8 11 12
3 9 12 13
column1 column2 column4 column5
1 4 10 11
2 5 11 12
3 6 12 13
column1 column2 column3 column5
1 4 7 11
2 5 8 12
3 6 9 13
column1 column2 column3 column4
1 4 7 10
2 5 8 11
3 6 9 12

Please note that it is extremely important that this be done IN A LOOP, so as to be replicable for an arbitrary number of columns, as I have managed to code this for a known number of columns already.

Thank you in advance for any help.

CodePudding user response:

That's a pretty straightforward problem for Matlab or Octave. I wonder what your problem was?

m = [
  1 4 7 10 11
  2 5 8 11 12
  3 6 9 12 13
];

outmatrices = {};

for col = 1:size(m,2)
  outmatrices{end 1} = [m(:,1:col-1), m(:,col 1:end)];
end

outmatrices

CodePudding user response:

You could use arrayfun( ) for this, which will handle any matrix size and hide the looping behind the function call. E.g.,

result = arrayfun(@(k)[m(:,1:k-1),m(:,k 1:end)],1:size(m,2),'uni',false);

The result will be a cell array with the various matrices as the cell elements.

  • Related