Reputation: 48986
Say we have the following matrix
1 3 6
5 4 7
5 3 9
What I'm trying to do is for each row, I assign it the maximum
value of the column. So, for instance, I'm expecting the following output:
x(1) = 6
x(2) = 7
x(3) = 9
I tried doing that using by writing the code below, but didn't get the expected putput:
x=[1 3 6;5 4 7; 5 3 9]
[rows, columns] = size(x);
for i=1:columns
for j=1:rows
[maximum, position] = max(x(j,:));
disp('MAXIMUM')
x(j)=maximum
end
end
What should I do to get the expected output?
Upvotes: 1
Views: 75
Reputation: 17036
You can use the built-in max
function with a dimension specifier: max(x,[],dim)
.
In your case, assuming your matrix is called A
:
>> x=max(A,[],2)
ans =
6
7
9
Upvotes: 3
Reputation: 8391
If I understood correctly your question, you can just use the max
function. It naturally operates on columns, therfore, some transposition is necessary.
x=[1 3 6;5 4 7; 5 3 9]
y = max(x')'
y =
6
7
9
You can even reassing the values on the fly
x = max(x')'.
Upvotes: 2