comparing and addition of two matrices

a=[9,41,48,0,0,0,0,0;15,47,56,0,0,0,0,0;25,67,0,0,0,0,0,0];b=[21;11;30]; I am having three rows in a and b. I need to compare a with b for example i am taking 21 from b and comparing with the first row of a, first row first column value is 9, but b value is 21 its greater than a so the remaining columns in first row should be added by 5 except zero [9, 46, 53,0,0,0,0,0]. Similarly in the second row of a has to be compared with second row of b [20,52,61,0,0,0,0,0]. Third row [25,72,0,0,0,0,0,0]. Finally my a=[9,46,53,0,0,0,0,0;20,52,61,0,0,0,0,0;25,72,0,0,0,0,0,0]. suggest with some points.

4 commentaires

José-Luis
José-Luis le 10 Juin 2014
Modifié(e) : José-Luis le 10 Juin 2014
I think if you just write out the pseudo code for this problem, then it would be easy for you to replace that with code
for each row in a do
if first element of row is less than equivalent row element of b do
find all elements of this row from second index to end that aren't
zero and add five
end
end
The loop and the if are easy (if stuck, type help size to see how size can be used to determine the number of rows in a) and then to find all elements that aren't zero, type help find for hints.
dpb
dpb le 10 Juin 2014
That isn't quite the rule he gave, though--he adds for all columns from 2:end irrespective of the first column comparison; it's only that first column that is dependent on the value in b, apparently. (At least that's what his example gives as a result.)
Geoff Hayes
Geoff Hayes le 10 Juin 2014
Huh. I could have sworn the second row of b didn't have 5 added to the elements from 2:end. I see now how it does from 1:end though...

Connectez-vous pour commenter.

 Réponse acceptée

dpb
dpb le 10 Juin 2014
Look up "logical addressing"...
>> ix=[b<a(:,1) a(:,2:end)>0];
>> a(ix)=a(ix)+5
a =
9 46 53 0 0 0 0 0
20 52 61 0 0 0 0 0
25 72 0 0 0 0 0 0

2 commentaires

Bathrinath
Bathrinath le 11 Juin 2014
Thank you sir. I bow you for your logical thinking.
dpb
dpb le 11 Juin 2014
Chuckles...thanks, glad I did seemingly get the intent correct; wasn't really sure if the actual example really was what was intended or not.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Question posée :

le 10 Juin 2014

Commenté :

dpb
le 11 Juin 2014

Community Treasure Hunt

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

Start Hunting!

Translated by