Help with the zeros function

1 view (last 30 days)
Tab for Lab
Tab for Lab on 20 Sep 2015
Commented: Tab for Lab on 20 Sep 2015
I am well aware that we can easily delete arrays of a vector using the [ ] function.
I however need to replace certain rows/ columns of my vector with zeros.
So how do I go on about doing that? Its really confusing because 'zeros' is mainly used to make a matrix full of zeros.
Also. Once we have that row/ column replaced with zero, how would we get rid of it without using [ ]. I know [ ] would be ideal and more efficient but i am trying to work with the zeros function specifically.
for example:
A = [1 2 3 4
9 1 2 2
3 4 2 2]
B = (length(zeros(:,3)))<-- I know this is wrong but something like this should work.
>>>B =
>>>1 2 3 4
0 0 0 0
3 4 2 2
C = 1 2 3 4
3 4 2 2
Then we remove the row we replaced. So we basically need to delete the row we have saved in variable B.
How would we do it?
Thanks

Answers (2)

Walter Roberson
Walter Roberson on 20 Sep 2015
B(2,:) = zeros(1,size(B,2));
Or just
B(2,:) = 0;
To get rid of rows that are all zero (even if not specifically written over but just happen to have that value):
B = B(any(B,2),:);

Image Analyst
Image Analyst on 20 Sep 2015
Try this:
B = A; % Initialize
B(2,:)=0 % Set all elements of row 2 to 0
% Make C
C=B([1,3],:)
  3 Comments
Walter Roberson
Walter Roberson on 20 Sep 2015
B(2,:) = zeros(1,size(B,2)); is the same as B(2,:)=0 for all practical purposes, but is slightly slower than B(2,:)=0 . You would typically use zeros() when you are allocating a block of memory at execution time that has to be all 0. For example,
C = zeros(3,5);
allocates a 3 x 5 block of double precision 0's and assigns it to C, either defining that variable for the first time or overwriting its value completely. On the other hand
C = 0;
would only assign a single double precision 0 to C, either creating C for the first time or overwriting its value completely. And
C(:) = 0;
would write a 0 of C's current class to all the elements of C, retaining C's current shape and using the same block of memory that it already has, with it being an error if C does not already exist.
Tab for Lab
Tab for Lab on 20 Sep 2015
Thanks buddy.
cheers.

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!