gpt4 book ai didi

arrays - 比较并查找二维数组中的字符串

转载 作者:行者123 更新时间:2023-12-02 11:34:20 24 4
gpt4 key购买 nike

我是 Matlab 新手,我陷入了有效解决以下问题的困境。

我有两个数组(都是二维的),我想逐个检查 array1 的列,以了解 array2 的每个列中出现了多少个元素(比较列与列)

例如

array1

---------
'a1' 'b1' 'c1'
'd1' 'e1' 'f1'

array2
----------
'a1' 'a1' 'b1' 'b1' 'a1'
'd1' 'd1' 'c1' 'd1' 'c1'
'c1' 'c1' 'b1' 'd1' 'd1'

我正在尝试获得以下输出

2 elements from array1 col1 appear in array2 col1
2 elements from array1 col1 appear in array2 col2
0 elements from array1 col1 appear in array2 col3
1 elements from array1 col1 appear in array2 col4
2 elements from array1 col1 appear in array2 col5

0 elements from array1 col2 appear in array2 col1
0 elements from array1 col2 appear in array2 col2
1 elements from array1 col2 appear in array2 col3
1 elements from array1 col2 appear in array2 col4
0 elements from array1 col2 appear in array2 col5

1 elements from array1 col3 appear in array2 col1
1 elements from array1 col3 appear in array2 col2
1 elements from array1 col3 appear in array2 col3
0 elements from array1 col3 appear in array2 col4
1 elements from array1 col3 appear in array2 col5
and so on

现在我尝试执行以下丑陋的代码以获得部分输出

for i=1:size(Array1,2)
for m=1:size(Array1,1)
element = Array1(i,m);

indx =find(ismember(Array2,element));
Array_match(indx) = Array_match(indx) + 1;
end
for s=2:size(Array1,1)
if length(char(Array1(s,i))) > 0
tt= tt + 1;
end
length(Array_test_words(s,i))
end
Indx2 = find((Array_match) > tt);
end

最佳答案

假设输入元胞数组包含单个字符串的所有单元格,这可能适合您 -

%// Input cell arrays
array1 = {
'a1' 'b1' 'c1'
'd1' 'e1' 'f1'}

array2 = {
'a1' 'a1' 'b1' 'b1' 'a1'
'd1' 'd1' 'c1' 'd1' 'c1'
'c1' 'c1' 'b1' 'd1' 'd1'}

%// Convert input cell arrays to numeric arrays
array1n = char(array1)-0
array1n = reshape(array1n(:,1) * 1000 + array1n(:,2),size(array1))

array2n = char(array2)-0
array2n = reshape(array2n(:,1) * 1000 + array2n(:,2),size(array2))

out = squeeze(sum(any(bsxfun(@eq,array2n,permute(array1n,[3 4 1 2])),1),3))

输出 -

out =
2 0 1
2 0 1
0 1 1
1 1 0
2 0 1

关于arrays - 比较并查找二维数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25766039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com