Dear All
I have a matrix of three column as below like the file provided, I would like to find the values from o or p columns which is the closest to q, I have written this code:
M=abs(o - q);
N=abs(p - q);
difference =[M N];
[~,ii] = min(difference,[],2);
if ii == 1
Result = o
else
Result = p
end
but it just return the p column to me, I am really confused about the results. I really appreciate your helps
Best Nima

3 件のコメント

Michal
Michal 2017 年 11 月 14 日
Add some test case data to your code and expected result.
Stephen23
Stephen23 2017 年 11 月 14 日
編集済み: Stephen23 2017 年 11 月 14 日
This conditional statement for if
if ii == 1
will only be true if all values of ii are equal to one, and by the way that you defined ii this is clearly not the case. That line does not operate element-wise on the elements of ii. You cannot use if to distinguish between different array values and cause different actions to happen without using a loop and indexing.
Even better would be to learn how to write vectorized code, in which case the loop is not required. These basic and important concepts for using MATLAB are explained in the Getting Started tutorials, which are highly recommended for all beginners:
What output do you expect to get?
Nima
Nima 2017 年 11 月 14 日
I expect this:

サインインしてコメントする。

 採用された回答

Oscar Briones
Oscar Briones 2017 年 11 月 14 日

1 投票

hola trabajé un poco en tu pregunta y lo solucioné de la siguiente manera,
%%Import the data
datos=xlsread('test1.xls','Sheet1','A2:D12');
%%Create output variable
q = datos(:,1);
o = datos(:,3);
p = datos(:,4);
M = abs (o - q);
N = abs (p - q);
R=M>N
result=o.*(1-R)+p.*(R)
saludos desde chile

1 件のコメント

Nima
Nima 2017 年 11 月 14 日
muchas gracias Oscar
lógica fantástica, realmente me gustó, mucho mejor que perder el tiempo en los enlaces provistos por las otras respuestas
lo siento, mi español es realmente malo

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

質問済み:

2017 年 11 月 14 日

コメント済み:

2017 年 11 月 14 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by