How to replace all the ones in a matrix with the string 'hey'?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
oshawcole
am 4 Dez. 2017
Kommentiert: Walter Roberson
am 6 Dez. 2017
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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 5 Dez. 2017
newmatrix = num2cell(matrix);
newmatrix(matrix == 1) = {'hey'};
8 Kommentare
Walter Roberson
am 6 Dez. 2017
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.
Weitere Antworten (1)
John D'Errico
am 4 Dez. 2017
You can't. A matrix is composed of numbers. You cannot insert a string for some elements, replacing an arbitrary numeric element.
0 Kommentare
Siehe auch
Kategorien
Mehr zu NaNs finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!