MATLAB: Comparing arrays using loop

for loopmatrix array

I need some help on assigning some codes. Say I have three matrices.
Matrix1= [cat;dog;hamster]
Matrix2=[7,6,1,5,8,1,9;4,6,10,15,8,1,9;3,6,25,5,8,4,10] %(this matrix represents how long a person watched them in their container).
Matrix3= [4,6,1,1,3,1,6;4,2,3,1,4,1,6;3,6,10,5,4,4,10] %(this matrix reprsents how many pets sold).
And each row in Matrix2 and Matrix 3 corresponds to the animal in that row in Matrix1 (ie. row 3 in Matrix2 and Matrix3 is for the hamster). How do i write a loop that says that if the total time watched is over 50 and amount sold is over 30 means that that pet is the most popular? I'm mainly stuck on where to put the FOR loop index (ie. for x=1:3)

Best Answer

You can actually do this in Matlab without needing a for loop. If I'm interpreting your question correctly, you're asking to find which row in a matrix contains the maximum sum. To achieve this, use the max and sum commands.
totWatch = sum(Matrix2,2); %Sum along dimension #2 (columns)
totBought = sum(Matrix3,2);
This gives us two vectors of 3x1 (cat, dog, hamster). Let's find which have a watch count above 50 AND a sell count above 30:
isPopular = (totWatch > 50) & (totBought > 30)
isPopular =
0
0
1
So strangely, hamsters are more popular than dogs. To find the most popular of each in an automated fashion you can use the max command, which can give you both the max value and the index of that value. For the most bought, for instance:
[maxB, ixB] = max(totBought)
maxB =
42
ixB =
3
Tells us that 42 pets of one type were sold, and this occurred in Row 3, the hamsters.
(edit: spelling)