I have three matrices. A=[8,1,6;3,5,7;4,9,2], B=[6,7,2;7,4,8;1,2,3], C=[4,8,5;3,2,1;1,1,1], . I want to find the maximum of A,B and C matrices. answer should be [8,8,6;7,5,8;4,9,3]. I used max(A,B,C) Command.but it is not working.Can any one help me.

1 commentaire

Don't store your data in lots of matrices: store your data in one ND array and then this task (and many others) becomes quite trivial:
max(array,[],dim)

Connectez-vous pour commenter.

 Réponse acceptée

Torsten
Torsten le 11 Fév 2016

2 votes

D = max(max(A,B),C)
Best wishes
Torsten.

6 commentaires

mahesh chathuranga
mahesh chathuranga le 11 Fév 2016
Thanks. But I have 57 matrices like this. writing command as this is quit difficult.
Torsten
Torsten le 11 Fév 2016
How are your matrices stored ? With names A, B, C, D,... ?
Best wishes
Torsten.
mahesh chathuranga
mahesh chathuranga le 11 Fév 2016
yes
Better store all of them in one big 3-dimensional matrix M of dimension 57x3x3.
Then just use
D=max(M,[],1)
Best wishes
Torsten.
Guillaume
Guillaume le 11 Fév 2016
Modifié(e) : Guillaume le 11 Fév 2016
It's not difficult to implement a function that will take an arbitrary number of matrices:
function max_matrices(varargin)
%MAX_MATRICES compute the maximum of several matrices
%syntax:
% mx = max_matrices(M1, M2, ...)
% mx = max_matrices(CellArayOfMatrices{:})
assert(nargin > 0, 'max_matrices requires at least one matrix');
mx = varargin{1};
for mxidx = 2:nargin
mx = max(mx, varargin{mxidx});
end
end
Note that you should prefer the second form shown under usage, that is store all your matrices into a cell array.
edit: And actually as per stephen's comment, a much simpler way is to just concatenate the matrix in a higher dimension, and one call to max would do it:
function max_matrices(varargin)
%MAX_MATRICES compute the maximum of several matrices
%syntax:
% mx = max_matrices(M1, M2, ...)
% mx = max_matrices(CellArayOfMatrices{:})
assert(nargin > 0, 'max_matrices requires at least one matrix');
dims = ndim(varargin{1})
mx = max(cat(dims + 1, varargin{:}), [], dims+1);
end
mahesh chathuranga
mahesh chathuranga le 11 Fév 2016
ok. Thank you both of you. wish you all the success in MATLAB

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by