(对于我的问题,我使用矩阵A
4x500000
。而A(4,k)的值在1到200之间变化。
我在这里给出一个例子A
4x16和A(4,k)在1到10之间变化。
我想首先将名称与1到5(= 10/2)的值匹配:
1 = XXY;
2 = ABC;
3 = EFG;
4 = TXG;
5 = ZPF;
我的目标是为矢量X找到矩阵A中的矩阵M:
A = [20 52 70 20 52 20 52 20 20 10 52 20 11 1 52 20
32 24 91 44 60 32 24 32 32 12 11 32 2 5 24 32
40 37 24 30 11 40 37 40 40 5 10 40 40 3 37 40
2 4 1 3 4 5 2 1 3 3 8 6 7 9 6 10]
A(4,k)取所有1到10之间的值。这些值可以重复,它们都出现在第4行。
20
X= 32 =A(1:3,1)=A(1:3,6)=A(1:3,8)=A(1:3,9)=A(1:3,12)=A(1:3,16)
40
A(4,1) = 2;
A(4,6) = 5;
A(4,8) = 1;
A(4,9) = 3;
A(4,12) = 6;
A(4,16) = 10;
对于对应于X的A(4,k),如果A(4,k)<= 5,则I关联2,如果A(4,k)> 1则关联1。 5.对于与X不对应的A(4,k)的其余值,我将0:
联系起来 [ 1 2 3 4 5 %% value of the fourth line of A between 1 and 5
2 2 2 0 2
ZX = 6 7 8 9 10 %% value of the fourth line of A between 6 and 10
1 0 0 0 1
2 2 2 0 2 ] %% = max(ZX(2,k),ZX(4,k))
最终目标是找到矩阵M:
M = [ 1 2 3 4 5
XXY ABC EFG TXG ZPF
2 2 2 0 2 ] %% M(3,:)=ZX(5,:)
答案 0 :(得分:1)
代码 -
%// Assuming A, X and names to be given to the solution
A = [20 52 70 20 52 20 52 20 20 10 52 20 11 1 52 20
32 24 91 44 60 32 24 32 32 12 11 32 2 5 24 32
40 37 24 30 11 40 37 40 40 5 10 40 40 3 37 40
2 4 1 3 4 5 2 1 3 3 8 6 7 9 6 10];
X = [20 ; 32 ; 40];
names = {'XXY','ABC','EFG','TXG','ZPF'};
limit = 10; %// The maximum limit of A(4,:). Edit this to 200 for your actual case
%// Find matching 4th row elements
matches = A(4,ismember(A(1:3,:)',X','rows'));
%// Matches are compared against all possible numbers between 1 and limit
matches_pos = ismember(1:limit,matches);
%// Finally get the line 3 results of M
vals = max(2*matches_pos(1:limit/2),matches_pos( (limit/2)+1:end ));
输出 -
vals =
2 2 2 0 2
为了更好地展示结果,您可以使用struct
-
M_struct = cell2struct(num2cell(vals),names,2)
输出 -
M_struct =
XXY: 2
ABC: 2
EFG: 2
TXG: 0
ZPF: 2
将结果写入文本文件 -
output_file = 'results.txt'; %// Edit if needed to be saved to a different path
fid = fopen(output_file, 'w+');
for ii=1:numel(names)
fprintf(fid, '%d %s %d\n',ii, names{ii},vals(ii));
end
fclose(fid);
文本文件的文本内容为 -
1 XXY 2
2 ABC 2
3 EFG 2
4 TXG 0
5 ZPF 2
答案 1 :(得分:0)
基于bsxfun()
的方法。
假设您的输入是(N
可以设置为200):
A = [20 52 70 20 52 20 52 20 20 10 52 20 11 1 52 20
32 24 91 44 60 32 24 32 32 12 11 32 2 5 24 32
40 37 24 30 11 40 37 40 40 5 10 40 40 3 37 40
2 4 1 3 4 5 2 1 3 3 8 6 7 9 6 10]
X = [20; 32; 40]
N = 10;
% Match first 3 rows and return 4th
idxA = all(bsxfun(@eq, X, A(1:3,:)));
Amatch = A(4,idxA);
% Match [1:5; 5:10] to 4th row
idxZX = ismember([1:N/2; N/2+1:N], Amatch)
idxZX =
1 1 1 0 1
1 0 0 0 1
% Return M3
M3 = max(bsxfun(@times, idxZX, [2;1]))
M3 =
2 2 2 0 2