Change the default filling of a matrix

6 visualizaciones (últimos 30 días)
Benoît
Benoît el 10 de Oct. de 2016
Editada: Thorsten el 10 de Oct. de 2016
Hi,
When I write
A(2,2)=10;A
I get something like
A =
0 0
0 10
So, the not specified elements are 0 by default. Is it possible to change this? Such that when writing the same command (A(2,2)=10), I get
A =
NaN NaN
NaN 10
Thank you for your answers! (I already know that a simple solution is to initialize A with A=NaN(2,2), but I want to avoid initialization of the variable, because its size is not a priori known).

Respuestas (2)

Guillaume
Guillaume el 10 de Oct. de 2016
Well, the size is obviously know at the moment you do the assignment. Either the matrix is smaller (or does not exist) before you do the assignment, in which case you can allocate the extra NaNs or it's big enough and already filled with NaNs, so you have nothing to do. So you could just write a function that checks the size before assignment and grow as appropriate.
Alternatively, if you're never going to assign 0, convert all the 0s to NaN when you are done:
A(A == 0) = NaN;
Alternatively, if some 0 can be assigned, store the values in a cell array, convert empty cells to NaN when you're done and finally convert to matrix:
clear A;
A{2,2} = 10;
%...
%done with all the assignments
A(cellfun(@isempty, A)) = {NaN};
A = cell2mat(A);

Thorsten
Thorsten el 10 de Oct. de 2016
Editada: Thorsten el 10 de Oct. de 2016
I do not know anyway to change the default behaviour of Matlab to fill the empty positions with zeros. So you have to do it in two steps:
A = nan(2,2);
A(2,2) = 10;
There is no
A(2,2,'init with NaN') = 10;

Categorías

Más información sobre Logical 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