替換串號我在MATLAB 例如,數字數組,在MATLAB陣列
a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
,我想用繩子來代替數字。
例如,1 =「蘋果」; 2 =「你好」; 3 =「再見」;
我能夠例如更換其他號碼如,
a(a==1) = 999
a(a==2) = 998
但我需要用字符串替換來完成同樣的事。對我來說不容易,有人能幫助我嗎? 謝謝,馬蒂爾德
替換串號我在MATLAB 例如,數字數組,在MATLAB陣列
a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
,我想用繩子來代替數字。
例如,1 =「蘋果」; 2 =「你好」; 3 =「再見」;
我能夠例如更換其他號碼如,
a(a==1) = 999
a(a==2) = 998
但我需要用字符串替換來完成同樣的事。對我來說不容易,有人能幫助我嗎? 謝謝,馬蒂爾德
如果你的號碼總是先從1
,每個號碼應及時更換,這只是索引:
>> mp={'apples','hello','goodby'}
mp =
'apples' 'hello' 'goodby'
>> a = [1 1 1; 2 2 1; 3 3 2]
a =
1 1 1
2 2 1
3 3 2
>> mp(a)
ans =
'apples' 'apples' 'apples'
'hello' 'hello' 'apples'
'goodby' 'goodby' 'hello'
這可能是一個方法來處理字符串和數字的混合數據的單元格陣列輸出 -
%// Numeric array and cell array of input strings
a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
names = {'apples','hello','goodbye'}
%// Create a cell array to store the mixed data of numeric and string data
a_cell = num2cell(a)
%// Get the mask where the numbers 1,2,3 are which are to be replaced by
%// corresponding strings
mask = ismember(a,[1 2 3])
%// Insert the strings into the masked region of a_cell
a_cell(mask) = names(a(mask))
代碼運行 -
a =
1 1 1
2 2 1
3 3 2
4 5 1
names =
'apples' 'hello' 'goodbye'
a_cell =
'apples' 'apples' 'apples'
'hello' 'hello' 'apples'
'goodbye' 'goodbye' 'hello'
[ 4] [ 5] 'apples'
我不知道,如果你真的想replace
的值或創建一個與它的字符串相同大小的新數組。正如其他人指出的,你需要一個單元陣列來存儲字符串。
a = [1 1 1; 2 2 1; 3 3 2; 4 5 1];
aStrings = cell(3,4)
aStrings(a==1) = {'apples'}
這個很漂亮!非常感謝Daniel – Matilde 2015-03-02 23:44:28