Delete element from row, shift the row and add a nan at the end of the row efficiently
Show older comments
Say that we have a matrix A
A =
1 2 3 4 5
5 4 3 2 1
I want to delete number 3 for example in the first row so that I get:
A =
1 2 4 5 nan
5 4 3 2 1
(Please note that the efficiency is the main concern in my question)
Possible solution is:
A(1,:)= [A(1,1:2) A(1,4:5) nan]
However, as my matrix is big, and I want to do this operation frequently, I want to know how I can do this in an efficient way if any?.
thank you.
Answers (2)
Shashank Prasanna
on 6 May 2013
A = [1 2 3 4 5;5 4 3 2 1];
[~,n] = size(A);
r = 2; % Number to be removed and replaced with nan in the end.
A(1,:) = circshift(A(1,:)',n-r)';
A(1,end) = NaN;
disp(A)
Jan
on 6 May 2013
0 votes
Operating on rows of a matrix is less efficient than on columns, because the processor can access neighboring elements of the RAM faster. Therefore it might be more efficient to transpose the matrix.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!