如何从Matlab矩阵的每一列中选择条目,以使其总和等于已指定的数字?

问题描述 投票:0回答:2

澄清我的问题的一个例子是,假设一个矩阵A = [0.8147 0.9134; 0.9058 0.6324; 0.1270 0.0975];我想从每一列中选择条目,以使它们的总和始终等于或近似等于上述矩阵的数字“ 1”。从第一列和第二列中选择的条目分别为0.9058和0.0975,这将导致总和为1(大约0.9058 + 000975 = 1.0033)或任何其他可能的组合,导致总和为“ 1”。我该怎么办?

matlab simulink
2个回答
0
投票

这可以通过简单的循环轻松实现:

A = [ 0.8147 0.9134; 0.9058 0.6324; 0.1270 0.0975]
n = size(A,1);
indeces_first_column = [];
indeces_second_column = [];

for i = 1:n
    indx = ismembertol(A(i,1) + A(:,2),1,0.01);
    if any(indx)
       indeces_first_column = [indeces_first_column i];
       indeces_second_column = [indeces_second_column find(indx)];
    end
end

results = [A(indeces_first_column,1) A(indeces_second_column,2)]
results =

0.9058    0.0975

在我的解决方案中,我遍历第一列中的元素,将它们添加到第二列中的所有元素。然后,我使用ismembertol检查总和是否接近1,且阈值为0.01。如果满足该条件,我将存储这些元素的索引。


0
投票

可能不是最雄辩的解决方案,但我认为它应该可以完成工作。您可能需要将数字四舍五入到1.0左右的有效位数,才能获得所需的确切答案。

此解决方案在A的第1列中的每个值与A的第2列中的每个值之间循环一次,因此,第1列中的值可能总和大于〜1,因此可以重复。要仅查找第一个匹配项,如果已经有答案,则可以在循环中引入“中断”,或者如果只希望包含一个可能的匹配项,则可以使用sub_matrix查找最接近1的总和。

% Define matrix: 
A = [ 0.8147 0.9134; 0.9058 0.6324; 0.1270 0.0975];

% Loop through column A to sum with each value in column B
% if the value is equal to 1.0, then it will group the pair numbers in 
% Matched_up matrix and the indices of the match from the original 
% matrix in Matched_indices matrix. 

Matched_up = [];
Matched_indices = [];

for indexA = 1:length(A)
    for indexB = 1:length(A)
        if round(A(indexA,1)+A(indexB,2),1) == 1.0
            Matched_up = [Matched_up; A(indexA,1) A(indexB,2)];
            Matched_indices = [Matched_indices; indexA indexB];
        end
    end
end

% Pair up values and check:
Row_sum = sum(Matched_up,2);

% If what you are ultimately after is the row which has a sum closest to 1
% You could look at the abs difference between the row_sum and 1

[Abs_diff, Row_Closest_to_one] = min(abs(1-Row_sum));
© www.soinside.com 2019 - 2024. All rights reserved.