Best way to retrieve items from a cell array using a cell array of indices?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
NV
el 16 de En. de 2025
Comentada: Star Strider
el 17 de En. de 2025
Hi I am porting a script I had in Python to Matlab. Also returning to MATLAB after a decade, so pardon me if it's too basic.
The key issue I am having is, retrieving premapped items from a cell array. Example, I have:
label_names={"assds", "Sasas", "Asasa", "assds"}
indices={[1 3 2]} %note that this can have varying lengths from 1 to full length of the label array.
label_names(indices) %of course returns an error
Error is "Unable to use a value of type cell as an index."
What is the best way to achieve this - retreive items based on a cell array of indices - as cleanly as possible?
PS: The reason they are cell arrays has to do with varying lengths. To avoid X-Y problem, lets assume rest of the code is done optimally.
Thanks!
2 comentarios
Walter Roberson
el 16 de En. de 2025
If the cell array always has exactly one element, then why use a cell array?
If the cell array potentially has more than one element, then what is the intended meaning? Should the different elements be used as different subscript positions? If the cell array was {[1 3], [2 4]} then should the call be equivalent to X([1 3], [2 4]) producing a 2 x 2 output, or should it be [X(1,2), X(3,4)] producing a 1 x 2 output ?
Respuesta aceptada
Star Strider
el 16 de En. de 2025
Editada: Star Strider
el 16 de En. de 2025
Creating ‘indices’ as a cell array is the problem.
Refer to it as a double array instead —
label_names={"assds", "Sasas", "Asasa", "assds"}
indices=[1 3 2] %note that this can have varying lengths from 1 to full length of the label array.
label_names(indices)
Equivalently (although redundantly) —
label_names={"assds", "Sasas", "Asasa", "assds"}
indices={[1 3 2]} %note that this can have varying lengths from 1 to full length of the label array.
label_names(indices{:})
.
EDIT — Corrected typographical errors.
.
2 comentarios
Star Strider
el 17 de En. de 2025
As always, my pleasure!
There is cerrtainly nothing wrong with using a cell array if that works for you.
Más respuestas (0)
Ver también
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!