2015-11-01 22 views
0

我想找出一種方法來做一個for循環,在這個循環中我可以比較兩個單元格,這會給我兩種不同的方法。一個用於char類,另一個用於class double。如何僅循環訪問單元格數組的某些部分?

這是我到目前爲止。

V = {2; 'tree'; 3; 'hope'}; 
W = {2; 'tree'; 3; 'hope'}; 


for i = 1:length(V); 
    if isequal(class(V{i}), 'double') 
     num = V{i} 
    elseif isequal(class(V{i}), 'char') 
     str = V{i} 
    end 
end 
for i = 1:length(W); 
    if isequal(class(W{i}), 'double') 
     acc_n(i) = isequal(V{i}, W{i}) 
    elseif isequal(class(W{i}), 'char') 
     acc_s(i) = strcmp(V{i}, W{i}) 
    end 
end 
mean_d = mean(acc_n) 
mean_s = mean(acc_s) 

我得到的輸出是:

acc_n = 
    1  0  1 
acc_s = 
    0  1  0  1 
mean_d = 
    0.6667 
mean_s = 
    0.5000 

我想輸出是:

1 1字符串,mean = 11 1爲雙倍,mean = 1

我該如何做一個循環,它只需要單獨的單元格的數字和單元格的單詞?

是否有任何可能的方式來循環單詞或數字?

回答

0

您可以首先提取字符串和雙打,並分別對待它們,這將避免循環。

V = {2; 'tree'; 3; 'hope'}; 
W = {2; 'tree'; 3; 'hope'}; 

VChar=V(cellfun(@ischar,V)); 
WChar=W(cellfun(@ischar,W)); 

acc_s=VChar==WChar; 

VNum=cell2mat(V(cellfun(@isnumeric,V))); 
WNum=cell2mat(W(cellfun(@isnumeric,W))); 

acc_n=VNum==WNum; 

循環版本:我沒有測試過,但它應該可以工作。

%Assumes V and W have equal number of elements. 

acc_n=[]; 
acc_s=[]; 
for i=1:numel(V) 
    if isequal(class(V{i}), 'double') && isequal(V{i},W{i}) 
     acc_n=[acc_n true]; 
    elseif isequal(class(V{i}), 'char') && strcmp(V{i},W{i}) 
     acc_s=[acc_s true]; 
    end 
end 
+0

是否有另一種方法來做到這一點,而不使用cellfun? – user2924450

+0

另外,如何使用循環來做到這一點? – user2924450

+0

@ user2924450我認爲循環會很好,因爲'cellfun'有時比循環更糟糕。見[這裏](http://stackoverflow.com/questions/18284027/cellfun-versus-simple-matlab-loop-performance)。看我的編輯。 –