2015-03-02 48 views
4

替換串號我在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 

但我需要用字符串替換來完成同樣的事。對我來說不容易,有人能幫助我嗎? 謝謝,馬蒂爾德

回答

5

如果你的號碼總是先從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' 
+0

這個很漂亮!非常感謝Daniel – Matilde 2015-03-02 23:44:28

3

這可能是一個方法來處理字符串和數字的混合數據的單元格陣列輸出 -

%// 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' 
+0

爲了簡化,最後一行可以替換爲'a_cell(mask)= names(a(mask))'。 – Daniel 2015-03-02 16:57:09

+1

@Daniel只是做了:) – Divakar 2015-03-02 16:57:41

0

我不知道,如果你真的想replace的值或創建一個與它的字符串相同大小的新數組。正如其他人指出的,你需要一個單元陣列來存儲字符串。

a = [1 1 1; 2 2 1; 3 3 2; 4 5 1]; 
aStrings = cell(3,4) 
aStrings(a==1) = {'apples'}