2016-08-17 104 views
0

我正在學習Matlab,並且正在編寫代碼以根據使用'if'的條件來查找特定值。值可以很容易地找到,但我想知道這個值是由陣列A和B的哪些元素創建的。不幸的是,我不能使用這個代碼。我真的很感激你的關注。使用Matlab將值賦給循環中的變量

A=[2,7,1,3,10]; 
B=[2,7,1,3,10]; 
c=1; 
k=0; 
f=0; 
L=length (A); 
for m=1:L-1 
    for n=m:L 
    if(A(m)./B(n)> 0.09 && A(m)./B(n)<c) 
     c=A(m)./B(n); 
     k=A(m); 
     f=B(n); 
     end 
    end 
end 

fprintf('the c value is %0.5f',c) 
fprintf('the A(m) value is %0.5f',k) 
fprintf('the B(n) value is %0.5f',f) 
the c value is 0.10000 
+1

,正嗎? –

回答

0

只是不停的位置k和f與你爲什麼不創建2個變量來存儲m的值指的是

for m=1:L-1 
    for n=m:L 
    if(A(m)./B(n)> 0.09 && A(m)./B(n)<c) 
     c=A(m)./B(n); 
     k=m; %keeping the position 
     f=n; %keeping the position 
     end 
    end 
end 

if (f==0 || k==0) %if f or k is zero 
    fprintf('No solution found\n')  
else 
    fprintf('the c value is %0.5f \n',c) 
    fprintf('the A(m) value is %0.5f at position %i \n',A(k),k) 
    fprintf('the B(n) value is %0.5f at position %i \n',A(f),f) 
end 
+0

你不需要'./'進行標量分割,而是使用'/'。 – NKN

+0

點了。我只是看着[k,f]部分 – Finn

+0

我試過了,但有一個錯誤:「下標索引必須是真正的正整數或邏輯。」 – Naz