how to declare all the rows and all column in matlab in a matrix or array??
Show older comments
suppose i need to remove all the zeros from a dataset and within a if else condition if the i no rows found zeros with all its column then the entire row will be deleted .. i need to know how to declare the entire row with column in matlab
is this the way to write c(:)=[]
Accepted Answer
More Answers (2)
James Tursa
on 9 Mar 2015
Edited: James Tursa
on 9 Mar 2015
c(:) is the syntax for the entire matrix, not a particular row. And when used on the rhs of a statement it means "reshape c as a column vector". For a 2D matrix, syntax for the k'th row is
c(k,:)
However, deleting the k'th row in a loop has the effect of resizing the array in a loop (can be very slow if many rows of a large matrix are deleted). Also, depending on how you do it, the indexing of your original problem can change if the k'th row suddenly disappears. Can you show more code for how you intend to do this, particularly if it is in a loop?
1 Comment
wasima tammi
on 9 Mar 2015
Edited: dpb
on 9 Mar 2015
dpb
on 9 Mar 2015
The commented-out line deleting the row will, as James noted, break as the array will then have a size(C1,2) one less than the original length (which, btw, will only be correct to begin with if there are more rows than columns in the array) so you will then "run off" the end later on.
As he also said, to do this in a loop requires traversing from last to first as
for i=size(T,1):-1:1
...
to not have the problem. But again (as noted also by James) this will also cause a continual reallocation of memory every time it does occur and will be much less efficient than the illustrated use of any supplied function and logical addressing.
The portion
if find (T(i,j)==1)
c1(i,:)=P(i,:);
is also amenable to logical addressing almost identically as to previous
idx=any(T==1),2);
c1(idx,:)=P(idx,:);
NB: the above two cases are two separate logical index vectors using the same variable over; it is also possible to write the expression entirely w/o the temporary variable but that means writing the logical test expression twice; once on each side of the assignment. I'm not sure if the JIT compiler is smart enough to recognize the duplicate operation and do the comparison only once or not; unfortunately TMW doesn't document behavior well enough to know so writing using the temporary ensures the one-time calculation at perhaps expense of some memory. It is also somewhat easier to see what's actually being done so there's some advantage in that, too, particularly for new users.
Categories
Find more on Startup and Shutdown 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!