我有一些数据,我想从中获取一些信息。但是,我遇到了一些问题,我很乐意得到专家的帮助。
数据和一些信息:
A = [1 0 -1 2 0 1;0 2 1 0 1 -2;1 1 0 2 1 1]%matrix
B = [1 3]#rows 1 and 3 are rows for searching.
struc.names = ['blue', 'red', 'green', 'amber', 'grey','yellow']% a structure of column names.
required.names = {'blue', 'green', 'grey','yellow'}; % a structure of required column names
我试图获得以下3种类型的信息:
首先:获取并保存行子集的矩阵。
第二:我想获得一个对应于感兴趣的列(required.names)的向量(填充1或0)与struc.names相比
第三:对于第1行和第3行,当行元素非零时,找到struc.names和required_rows之间的匹配项;也可以根据匹配数量排列结果输出。
问题1:
code for getting matrix:
struc.names = {'blue', 'red', 'green', 'amber', 'grey','yellow'};
required_rows = [1 3];
for k = 1:length(required_rows);
% open file for writing
fid =fopen('ouput.txt','w');
idx(k,:) = A(required_rows(k),:);
fprintf(fid,'%d \n',idx);#print matrix
end;
获得的输出:
1 0 -1 2 0 1 1 1 0 2 1 1
必需的输出:
1 0 -1 2 0 1
1 1 0 2 1 1
问题2:与struc.names相比,获取required.names = {'blue','green','gray','yellow'}的列向量;
我想在一个向量中获得1(列名存在)和0(列名不存在):[1 0 1 0 0 1];我不确定如何编写代码。
问题3:当行元素非零时查找struc.names和required_rows之间匹配的代码,然后获得根据匹配数排列的排序结果。代码:
struc.names = ['blue', 'red', 'green', 'amber', 'grey','yellow']# a structure of column names.
required.names = {'blue', 'green', 'grey','yellow'}; # a structure of required column names
struc.names = {'blue', 'red', 'green', 'amber', 'grey','yellow'}
required_rows = [1 3];
% open file for writing, and Loop
fid=fopen('file.txt','w+');
for K = 1 : length(required_rows);
idx = A(required_rows(K),:) ~= 0;
if any(idx)
struc.names = struc.names(idx)
C = intersect(struc.names ,required_rows)
fprintf(fid, 'row A(%d,:) has the following matches:\n');
fprintf(fid, '%s ', C{idx} );
fprintf(fid, '\n');
end
end
fclose(fid);
排序输出(根据匹配数量)所需:
row 3: blue red amber grey yellow
row 1: blue green amber yellow
谢谢
答案 0 :(得分:2)
问题1。
A(required_rows,:)
ans =
1 0 -1 2 0 1
1 1 0 2 1 1
问题2。 您可以使用intersect在struct.names中查找required.names。 intersect查找两组的公共元素。看看help。第二个参数返回struct.names中交集的索引。事实上,struct.names {match}存在于required.names中。
v=zeros(1, numel(struct.names));
[~, match] = intersect(struct.names, required.names);
v(match)=1
v =
1 0 1 0 1 1
问题3。
idx = A(required_rows,:) ~= 0;
[~,perm] = sort(sum(idx,2),'descend');
for i=1:length(perm)
matches = struct.names(idx(perm(i), :));
display(['Row ' num2str(required_rows(perm(i))) ' has the following matches: ' ...
sprintf('"%s" ', matches{:})]);
end
Row 3 has the following matches: "blue" "red" "amber" "grey" "yellow"
Row 1 has the following matches: "blue" "green" "amber" "yellow"
要获得每行中匹配的百分比,您需要将匹配中的元素数除以struct.names中的元素数:
numel(matches)/numel(struct.names)*100