开发者

store index of matrix for minimum

I have a 2d matrix Ac(yr,j).

I want it to compare each value of it with another 1D array and store the value of array for which absolute minimum is coming.

for 开发者_StackOverflowyr=1:32,  
   for j=1:12,  
       for in=1.5:1:32.5,  
            actin=Ac(yr,j);  
            kar(in-0.5)=abs(in-actin);  
            dab(yr,j)=min(kar(kar>=0));              
       end         
   end  
end  

I'm able to find the least positive value but not the value of in for which it is coming.


You need to call max as shown below in order to get the index instead of the value.

[~, dab(yr,j)] = min(kar(kar>=0));


In order to get rid of the nested loops you could try arrayfun. Define the operation to be performed on every array element.

function [index] = myMinFunction(value, data)
    [val, index] = min(abs(data - value));
end

Execute the defined operations.

dab = arrayfun(@(x)myMinFunction(x, in), Ac)


your code needs work, and I'm guessing in is the array you want to compare.

to start off, you can get rid of the third for loop and just do:

actin=Ac(yr,j);
kar = abs(in-actin)

the last expression puzzles me: kar is always >=0 (from the abs function) so you don't need to check for it... worse, it will always return 1! so yo u will always get the first index of kar. Have you tried:

dab(yr,j)=min(kar);

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜