Change the default filling of a matrix
5 次查看(过去 30 天)
显示 更早的评论
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).
0 个评论
回答(2 个)
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!