存储最小值的矩阵索引

发布于 2024-11-04 06:31:47 字数 383 浏览 3 评论 0原文

我有一个二维矩阵Ac(yr,j)
我希望它将它的每个值与另一个一维数组进行比较,并存储即将到来的绝对最小值的数组值。

for yr=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  

我能够找到最小的正值,但找不到它即将到来的 in 的值。

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 yr=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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寄与心 2024-11-11 06:31:47

您需要如下所示调用 max 才能获取 索引而不是

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

为了摆脱嵌套循环,您可以尝试 arrayfun。定义要对每个数组元素执行的操作。

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

执行定义的操作。

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

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)
迷乱花海 2024-11-11 06:31:47

您的代码需要工作,我猜测 in 是您要比较的数组。

首先,您可以摆脱第三个 for 循环,然后执行以下操作:

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

最后一个表达式让我困惑:
kar 总是 >=0 (来自 abs 函数),所以你不需要检查它......更糟糕的是,它总是返回 1!所以你总是会得到 kar 的第一个索引。你尝试过吗:

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

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);

?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文