How to get the "zero/blank" element of a given variable?

3 visualizaciones (últimos 30 días)
royk
royk el 29 de Ag. de 2019
Comentada: royk el 30 de Ag. de 2019
I have an array VAR of unknown type. When the array is extended, Matlab knowns how to fill in blank ("zero") values of the correct type. How do I get this default blank value for any given Var type?
One solution is simply to extend an array and see what value gets padded:
BLANK(2) = VAR(1) ; BLANK(2) = [] ;
This returns a scalar BLANK with the correct "0" value and works for any VAR type.
BUT: It doesn't work with empty VAR.
Any thoughts of a general way to get the Blank value for any given array even if empty?

Respuesta aceptada

Rik
Rik el 29 de Ag. de 2019
Editada: Rik el 29 de Ag. de 2019
You can abuse repmat for this:
a=uint8(8);
repmat(a,0,0)
b='foo_bar';
repmat(b,0,0)
Edit:
On second read, you might actually mean this instead:
a=uint8(8);b='foo_bar';c={'1',2};
get_blank_val=@(x) eval([class(x) '(0)']);
get_blank_val(a)
get_blank_val(b)
get_blank_val(c)
  7 comentarios
Rik
Rik el 29 de Ag. de 2019
You could put in a special condition for a struct, but then you can't make it an anonymous function anymore.
function blank=get_blank_val(x)
if ~isa(x,'struct')
blank=eval([class(x) '(0)']);
else
fn=fieldnames(x);
tmp=[fn repmat({[]},size(fn))]';
blank=struct(tmp{:});
end
end
royk
royk el 30 de Ag. de 2019
that will do the job
there are still other exceptions. for example, for an array of MyClass objects, Matlab determines Blank for array extension by calling empty(MyClass).
It thereby feels like there got to be a generic Matlab function that returns the Blank object for array extension for ANY type.
Anyway, your kind suggestion above surely does the job for my needs.
thanks!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Operators and Elementary Operations 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