2015-02-09 34 views
1

我想在一個矩陣中連接0和1來形成一個二進制數字(作爲一個字符串)。 例如,[1 0 1;0 0 1]應輸出['101';'001']連接在matlab中的數字

然而,嘗試此輸入時,我得到了['1','1']作爲結果。爲什麼?

function result = generateBinary(ref_matrix) 
    [row col] = size(ref_matrix); 
    result = cell(1,row); 

    str = ''; 

    for i=1:row 
     for j = 1:col 
      n = num2str(ref_matrix(i,j)) 
      str = strcat(str, num2str(ref_matrix(i,j)));  
      str 
     result{1,i} = str;  
     str = ''; 
     end 
    end  
end 
+1

你可以用char(ref_matrix +'0')替換這個函數' – Daniel 2015-02-09 02:15:34

回答

1

第一個end是在錯誤的地方。

function result = generateBinary(ref_matrix) 
[row col] = size(ref_matrix); 
result = cell(1,row); 

str = ''; 

for i=1:row 
    for j = 1:col 
     n = num2str(ref_matrix(i,j)) 
     str = strcat(str, num2str(ref_matrix(i,j)));  
     str 
    end 
    result{1,i} = str;  
    str = ''; 
end 

由於縮進建議,result{1,i} = str;str = '';可能不是內循環的一部分。