How do I retrieve individual elements from an object all at once?

2 visualizaciones (últimos 30 días)
Hi all,
I have an Object where I'd like to retrieve all elements at once instead of through a loop.
My object is set up like this:
ObjArr
# Item one First Name
# Item two Last Name
Instead of using code like this...
for k = 1:n
tempSTR{k} = ObjArr(k).Name;
end
...I'd like to use something like the code below to quickly pull out a vector of data across all elements.
tempSTR{} = ObjArr.Name;
Please help.
Thanks,
jason

Respuesta aceptada

Sven
Sven el 13 de Jul. de 2012
Editada: Sven el 13 de Jul. de 2012
If the contents of your object's field is numeric, you can make a matrix like this:
myNumVector = [Object.myNum];
To get a cell of non-numeric data such as strings (or a cell of anything, really), just use:
myVarCell = {Object.myVar};
Or, to use your code:
for k = 1:n
tempSTR{k} = ObjArr(k).Name;
end
... can be replaced with:
tempSTR = {ObjArr.Name};
  2 comentarios
Daniel Shub
Daniel Shub el 13 de Jul. de 2012
I think it should be
tempSTR = {ObjArr(1:n).Name};
Since we don't know how big ObjArris.
Jason
Jason el 13 de Jul. de 2012
Thanks all, both methods work, at least when pre-allcoating the size of the tempSTR. I also have double arrays and using [ ] instead of { } works there.

Iniciar sesión para comentar.

Más respuestas (1)

Daniel Shub
Daniel Shub el 13 de Jul. de 2012
Loren's blog has a post about OOP performance. Looping outside the object is slower than looping inside the method. You probably want to overload SUBSREF and get.Name to handle arrays.

Categorías

Más información sobre Loops and Conditional Statements 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