Fill a matrix with same values

Hi! I have a matrix like this:
[ 1 8 9 7 7 4]
[ 0 0 0 0 0 0]
[ 0 0 0 0 0 0]
[ 9 8 6 5 5 1]
[ 0 0 0 0 0 0]
And I want to fill it like this
[ 1 8 9 7 7 4]
[ 1 8 9 7 7 4]
[ 1 8 9 7 7 4]
[ 9 8 6 5 5 1]
[ 9 8 6 5 5 1]
It seems to be very easy, but I cannot realize how to do it. Thank you in advice!

 Accepted Answer

Matt J
Matt J on 20 Oct 2012
Edited: Matt J on 20 Oct 2012
Another way,
e=find(any(A,2));
[h,b]=histc(1:size(A,1),[e;inf]);
A=A(e(b),:);

7 Comments

Nice!
I think this would be somewhat faster:
I = any(A,2);
F = find(I);
A = A(F(cumsum(I)),:);
Of course not faster than
A =[ 1 8 9 7 7 4
1 8 9 7 7 4
1 8 9 7 7 4
9 8 6 5 5 1
9 8 6 5 5 1]
Counting typing time? Ha! What about for:
N = 50000;
A = randi(10,N,10);
A(randperm(N,floor(3*N/4)),:) = 0;
A(1) = 9; % First row is not zero
|I think this would be somewhat faster:
I = any(A,2);
F = find(I);
A = A(F(cumsum(I)),:);|
Yes, perhaps!
Well like my answer below says, I'm not making any assumptions about being general, as in it might be different sizes or numbers than what he explicitly put there. Actually, this was a gentle hint to Alex and others who post this stuff all the time: "I have this, and I want that". And they don't say what might vary from one case/situation to another. So I say "just make that directly." like I did when I pasted what he wanted. If that doesn't work for them then they should say what allowances need to be made for the algorithm to work for them, like the number of rows or columns or values can vary, etc. It can waste people's time. For example if someone says I have [-2 -2] and I need [2 2] and someone says just take abs(A). Then they come back and say, "No, that doesn't work because when I put in [10 20] I get [10 20] when it should really be [14 24]" Well it did work for the one situation given but not for the later cases, only after which hearing do we learn that they really wanted A+4, not abs(A). Anyway, Matt - I'm sure you know all this.
I knew what you were saying, IA. I agree completely with your main point - a point we have discussed before (but it does bear repeating!).
Cheers!
+1 to Fig's comment-answer

Sign in to comment.

More Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 20 Oct 2012
Edited: Azzi Abdelmalek on 20 Oct 2012
A= [1 8 9 7 7 4
0 0 0 0 0 0
0 0 0 0 0 0
9 8 6 5 5 1
0 0 0 0 0 0]
for k=find(~all(A,2))'
A(k,:)=A(k-1,:)
end
You're all making assumptions of criteria Alex did not give. Making no assumptions whatsoever, this is the fastest way I can think of:
A =[ 1 8 9 7 7 4
1 8 9 7 7 4
1 8 9 7 7 4
9 8 6 5 5 1
9 8 6 5 5 1]

Categories

Find more on Mathematics 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!