Borrar filtros
Borrar filtros

Why is this function not recognizing the correct number of rows?

3 visualizaciones (últimos 30 días)
In this function I am taking a matrix m where each row holds a student's grades and each column is a different assignment, and returning the lowest of the highest grade that each student achieved in any assignment. When I do minmaxgrade([74, 72, 78; 67, 89, 90; 89, 92, 100; 100, 80, 90]) I am getting a weird answer, ans = 67 72 78 instead of just 78.
Here's my code:
function M=minmaxgrade(m)
[R,~]=size(m);
M=min(max(m,[],R));
end

Respuesta aceptada

Roger Stafford
Roger Stafford el 28 de Abr. de 2016
Change the line
[R,~]=size(m);
to
R = 2;
You want to do your maximizing along the second dimension, not the fourth. Your matrix doesn't even have four dimensions. Matlab should have issued an error message. Did it?
  2 comentarios
Stephen23
Stephen23 el 28 de Abr. de 2016
Editada: Stephen23 el 28 de Abr. de 2016
@ Roger Stafford: actually throwing an error would be inconsistent with the standard behavior of MATLAB, which assumes that all trailing dimensions have size one:
>> X = [74, 72, 78; 67, 89, 90; 89, 92, 100; 100, 80, 90]
X =
74 72 78
67 89 90
89 92 100
100 80 90
>> X(:,:,:,1) % look, no error!
ans =
74 72 78
67 89 90
89 92 100
100 80 90
>> max(X,[],4) % also no error!
ans =
74 72 78
67 89 90
89 92 100
100 80 90
This is actually perfectly consistent: because there are infinite trailing singleton dimensions we can access any of them using indexing, or apply operations along any of them. And of course any operation that operates along one particular dimension does not affect the other dimensions, e.g.:
>> Y = randi(9,1,2,3)
Y(:,:,1) =
7 1
Y(:,:,2) =
3 1
Y(:,:,3) =
1 8
>> sum(Y,2) % does not change dims 1,3,4,5,6,7,8,...
ans(:,:,1) =
8
ans(:,:,2) =
4
ans(:,:,3) =
9
which means that summing along the fourth (implicit trailing singleton) dimension) is never an error:
>> sum(Y,4) % does not change dims 1,2,3,5,6,7,8...
ans(:,:,1) =
7 3
ans(:,:,2) =
9 1
ans(:,:,3) =
4 4
Given that trailing dimensions are implicitly one:
it would be bizarre and inconsistent to treat accessing any trailing higher dimension as an error case.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by