我需要比较两个字符数组,使它们完全相同。同时,我需要我保存的字符的坐标。
例如,我有两个字符数组
A=['a';'b';'b';'b';'c';'d'];
B=['a';'b';'b';'d'];
我希望结果是
Anew=['a';'b';'b';'d'];
Bnew=['a';'b';'b';'d'];
我想知道的位置
APos=[1;2;3;6];
BPos=[1;2;3;4];
所以
Anew=A(APos);
Bnew=B(BPos);
我尝试了以下代码
[lmod1,lmod2]=size(A);
[lobs1,lobs2]=size(B);
PosB=zeros(lobs1,1);
for i=1:lobs1
for j=1:lmod1
if B(i,:)==A(j,:)
PosB(i,:)=i; %collect the ones that are in there, the zeros should then be the ones that are not
end
end
end
PosB2=PosB(PosB~=0);
PosA=zeros(lmod1,1);
for i=1:lmod1
for j=1:lobs1
if A(i,:)==B(j,:)% if this is true at the end of the loop, it means that the value of namesobs is in namesw
PosA(i,:)=i; %collect the ones that are in there, the zeros should then be the ones that are not
end
end
end
PosA2=PosA(PosA~=0);
但这只是检查是否存在,而不是在值重复不同次数的情况下。如何添加额外的过滤器,使字符串在两个字符串数组中重复相同的次数?
仅供参考,我正在处理的实际字符串如下:
>> ODates(1:10,:)
ans =
10×12 char array
'20100202_186'
'20100202_186'
'20100202_190'
'20100202_190'
'20100202_190'
'20100202_190'
'20100202_190'
'20100202_191'
'20100202_191'
'20100202_191'
ED日期(1:10,:(
ans =
10×12 char array
'20100202_186'
'20100202_190'
'20100202_190'
'20100202_190'
'20100202_190'
然后答案是:
新日期(1:10,:(
ans =
10×12 char array
'20100202_186'
'20100202_190'
'20100202_190'
'20100202_190'
'20100202_190'
通过循环解决这个问题是正确的,但我觉得你的想法有点太复杂了。查看此解决方案
A=['a';'b';'b';'b';'c';'d'];
B=['a';'b';'b';'d'];
% allocate logical vectors
lgA = false(size(A));
lgB = false(size(B));
% initialize loop control counter
ia0 = 1;
% looping
for ib = 1:length(B)
for ia = ia0:length(A)
% check if A == B and stop the looping over A if it is true
if A(ia) == B(ib)
% store
lgA(ia) = true;
lgB(ib) = true;
% update loop control counter to start from the current
% index the next time
ia0 = ia+1;
break
end
end
end
% validity check
assert( all(A(lgA) == B(lgB)) )
% output
APos = find(lgA);
BPos = find(lgB);