How to replace all the ones in a matrix with the string 'hey'?

matrix= [1 0 0.1 0.001 4; 5.9 2.1 3.15 8.95 1.11]
All the ones should be replaced with 'hey'
This is my code
matrix= [1 0 0.1 0.001 4; 5.9 2.1 3.15 8.95 1.11];
matrix= num2str(matrix);
matrix(matrix=='1') = 'h'
when I replace 'h' with 'hey' it gives me this error
matrix(matrix=='1') = 'hey'
I have just started to learn MATLAB. please help

 Respuesta aceptada

newmatrix = num2cell(matrix);
newmatrix(matrix == 1) = {'hey'};

8 comentarios

I want to replace all the ones, so 0.001 should look as 0.00hey. 1.11 should be hey.heyhey
newmatrix = char( regexp( cellstr(num2str(matrix)), '1', 'hey' ) )
(not tested)
oshawcole
oshawcole el 5 de Dic. de 2017
Editada: oshawcole el 5 de Dic. de 2017
Error using regexp Invalid option for regexp: hey.
newmatrix = char( regexprep( cellstr(num2str(matrix)), '1', 'hey' ) )
(Still not tested. My system is running a large program at the moment.)
oshawcole
oshawcole el 6 de Dic. de 2017
Editada: oshawcole el 6 de Dic. de 2017
matrix= [1 0 -1 0.001 4; 5.9 -1 3.15 1 1.11]
How can I replace the +1 and -1 with 'hey'? The answer should look like:
matrix= [hey 0 hey 0.001 4; 5.9 hey 3.15 hey 1.11]
newmatrix = regexprep( mat2str(matrix), {'\[', '\]', '(?<=\s|^)-?1(?=\s|$)'}, {'', '', 'hey'}, 'lineanchors')
is there a way to get it displayed as a matrix?
matrix= [1 0 -1 0.001 4; 5.9 -1 3.15 1 1.11 ];
cell_conv = (num2cell(matrix));
find_one = abs( matrix ) == 1 ;
cell_conv(find_one)={'hey'}
this is what I found? i just want to put this together in one line.
It is possible to do in one line, but it gets so messy that it is not recommended.
Here is a way to do it with the assistance of a helper function.
IDXAT = @(M,IDX) M(IDX);
disp(IDXAT(cat(3,num2cell(matrix),repmat({'hey'},size(matrix))), reshape(1:numel(matrix), size(matrix))+numel(matrix)*(abs(matrix)==1)))
The output would look like
'hey' [ 0] 'hey' [0.001] [ 4]
[5.9] 'hey' [3.15] 'hey' [1.11]
I am not sure that is acceptable to you.

Iniciar sesión para comentar.

Más respuestas (1)

John D'Errico
John D'Errico el 4 de Dic. de 2017
You can't. A matrix is composed of numbers. You cannot insert a string for some elements, replacing an arbitrary numeric element.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 4 de Dic. de 2017

Comentada:

el 6 de Dic. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by