Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 如何从矩阵的每一列中选取条目,使其总和等于已指定的数字?_Matlab - Fatal编程技术网

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

Matlab 如何从矩阵的每一列中选取条目,使其总和等于已指定的数字?,matlab,Matlab,澄清我的问题的一个例子是,让我们假设一个矩阵 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的任何其他可能组合。我该怎么做 编辑:这里,矩阵A3x2仅作为示例给出。实际矩阵相当大,有许多行和列。对于一个

澄清我的问题的一个例子是,让我们假设一个矩阵

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的任何其他可能组合。我该怎么做


编辑:这里,矩阵A3x2仅作为示例给出。实际矩阵相当大,有许多行和列。对于一个大型矩阵,任何彻底的搜索都会花费太多的时间。

可能不是最有说服力的解决方案,但我认为它应该完成这项工作。您可能需要在1.0中使用四舍五入的数字和有效数字的数量,以获得您想要的确切答案

此解决方案将A第1列中的每个值循环一次,A第2列中的每个值循环一次,因此第1列中的某个值可能多次总和为~1,因此可能会重复。要仅查找第一个匹配项,如果已经有答案,则可以在循环中引入一个中断,或者如果只希望包含一个可能的匹配项,则制作一个子矩阵以查找最接近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));

这里有一个简洁的方法来实现两列a

B = nchoosek(1:numel(A),2);
B(B(:,1)>length(A) | B(:,2)<(length(A)+1),:) = [];
S = sum(A(B),2);
P = A(B(S>.98 & S<1.02,:))  % Set your tolerance.  Here: abs(S-1)<0.02

我们鼓励StackOverflow上的人们自己尝试解决这个问题。你试过什么吗?总是只有两列吗?@Zobeenay ndgrid解决方案有什么问题吗?在问题中提到这一点也是个好主意。到目前为止,给出的所有答案都假设A中只有两列。这也应该在问题中。如果对所有可能性进行彻底搜索花费了太多时间,建议进行另一次彻底搜索可能不会有帮助。关于这些数据,你还有什么可以告诉我们的吗?你知道什么可能会减少搜索空间吗?