How to add some symbols into a matrix ?

In fact , I have a Matrix like X =
0 5.2 4.8 28.8
0 0 1.0 33.8
0 0 0 33.4
0 0 0 0
I would like to create like this
0 5.2 4.8 28.8
NaN 0 1.08 33.8
NaN NaN 0 33.4
NaN NaN NaN 0
I wrote something like this, but it does not work very well. because I would like to keep the first column and first row zero value, the second column second row zero value and so on
[m,n]=size (X) for i=1:m; for j=1:n; if X(i,j)==0 X(i,j)= NaN ; end end end

 Respuesta aceptada

Daniel Shub
Daniel Shub el 30 de Ag. de 2011
It depends on what you want to do with this matrix. If you just want it to be displayed nicely:
classdef partmat < double
methods
function obj = partmat(data)
if nargin < 1
data = [];
end
validateattributes(data, {'numeric'}, {'2d'})
obj = obj@double(data);
end
function disp(obj)
for irow = 1:size(obj, 1)
for icolumn = 1:size(obj, 2)
if ~isnan(obj(irow, icolumn))
x = num2str(obj(irow, icolumn));
else
x = '--';
end
fprintf(['\t', x]);
end
fprintf('\n');
end
end
end
end
Example:
>> x = partmat(magic(5))
x =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> x(3) = nan
x =
17 24 1 8 15
23 5 7 14 16
-- 6 13 20 22
10 12 19 21 3
11 18 25 2 9
If you want to get even fancier you could overload subsassgn and allow notation like
x(5) = '--'

3 comentarios

Niki
Niki el 30 de Ag. de 2011
what do you mean of classdef partmat < double?
i got error
Error: Illegal use of reserved keyword "classdef".
Daniel Shub
Daniel Shub el 30 de Ag. de 2011
What version of MATLAB are you using? The code needs to be saved into a file called partmat.m.
Niki
Niki el 30 de Ag. de 2011
I have all these versions 6.5 7.1 7.9 and 7.12

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 30 de Ag. de 2011
X(tril(true(size(X)),-1))=nan
add
X(bsxfun(@lt,1:4,(1:4)'))=nan
more
only for cell array
Xc = num2cell(X)
Xc(bsxfun(@lt,1:4,(1:4)'))={'-'}

4 comentarios

Niki
Niki el 30 de Ag. de 2011
Thanks for your prompt reply, if I would like to add something else like - symbol, then what should I do ?
Walter Roberson
Walter Roberson el 30 de Ag. de 2011
text symbols cannot appear in numeric matrices. If you want a number prefixed by "-" then probably the easiest way to do that is to multiply the number by negative 1. But it looks to me like perhaps you want an n-dash rather than a minus sign.
Andrei Bobrov
Andrei Bobrov el 30 de Ag. de 2011
I agree with Walter Robenson
Niki
Niki el 30 de Ag. de 2011
In fact both andrei answer are very nice and useful,
Walter no, I do not want to prefix a number by "-",
I just wanted to put "-" instead zero when I copied the output into a xls file
However it seems that Andrei second comment works well .
I put another question , please also take a look at it

Iniciar sesión para comentar.

Preguntada:

el 30 de Ag. de 2011

Community Treasure Hunt

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

Start Hunting!

Translated by