Borrar filtros
Borrar filtros

Is it possible to do multi index command in one line?

29 visualizaciones (últimos 30 días)
yoohooo's
yoohooo's el 28 de Abr. de 2021
Comentada: Steven Lord el 28 de Abr. de 2021
For example, if I want to get number of columns in an array I would have to do the following:
A = [1 2; 3 4];
mySize = size(A);
myCol = mySize(2);
It adds 2 lines and an extra variable in my code. Is it possible to put them in one line like:
myCol = size(A)(2);
Somthing similar to this because this is not the correct syntax.
Thank you very much!

Respuesta aceptada

Matt J
Matt J el 28 de Abr. de 2021
Editada: Matt J el 28 de Abr. de 2021
Not in general, but in the case of your example there is a shorter syntax,
myCol=size(A,2)
  2 comentarios
yoohooo's
yoohooo's el 28 de Abr. de 2021
Thank you very much. Ah, I forgot we can also do it this way. This is not a good example, then. But yea, so it's not possible.
Steven Lord
Steven Lord el 28 de Abr. de 2021
For some definition of "one line" it is. Write a function:
A = [1 2 3; 4 5 6];
sz = size(A) % for checking
sz = 1×2
2 3
y = getElement(size(A), 2) % The one line
y = 3
But this has a drawback that the shorter syntax doesn't.
size(A, 3) % A has trailing singleton dimensions
ans = 1
y2 = getElement(size(A), 3)
Index exceeds the number of array elements (2).

Error in solution>getElement (line 7)
y = x(whichone);
function y = getElement(x, whichone)
y = x(whichone);
end

Iniciar sesión para comentar.

Más respuestas (2)

Matt J
Matt J el 28 de Abr. de 2021
An approximation of this can be enabled through some incredibly convoluted OOP methods
It's not worth it...

Matt J
Matt J el 28 de Abr. de 2021
Editada: Matt J el 28 de Abr. de 2021
This is a generally applicable one line implementation, but probably not what you'd hoped for.
A = [1 2; 3 4];
myCol = subsref( size(A), struct('type','()','subs',{{2}}))
myCol = 2

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by