Change the default filling of a matrix

5 次查看(过去 30 天)
Benoît
Benoît 2016-10-10
编辑: Thorsten 2016-10-10
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).

回答(2 个)

Guillaume
Guillaume 2016-10-10
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 2016-10-10
编辑:Thorsten 2016-10-10
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;

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by