comparison and shifting strings/arrays with different length in matlab

南笙酒味 提交于 2019-12-07 21:38:24

问题


I have a list of strings or arrays with different length or size. I want to use the shortest string and compare with other strings by shifting the shortest string window one by one to do comparison.

Let's say I want to do addition, I have [2 1 3] as my shortest list and want to perform addition on [4 5 7 8 9]

1st addition: [2 1 3] + [4 5 7]
2nd addition: [2 1 3] + [5 7 8]
3rd addition: [2 1 3] + [7 8 9]

How can i do this using matlab?

Thanks


回答1:


A simpler approach, if you don't care much about speed is using arrayfun and cell2mat. Note that this approach doesn't check which vector is which. a must be shorter than b.

a =
     1     2     3
b =
     1     3     5     2     4     6

c = cell2mat(arrayfun(@(n) a+b(n:n+numel(a)-1), 1:numel(b)-numel(a)+1,'UniformOutput',0).')
c =
     2     5     8
     4     7     5
     6     4     7
     3     6     9



回答2:


Say A is the longer vector and B the shorter one. You can use hankel function to create a matrix where each row is a window of length 3 over A

>> hankel(A(1:3),A(3:end))
ans =
     4     5     7
     5     7     8
     7     8     9

Now you just need to call bsxfun to do the desired action on each row:

L=numel(B); 
bsxfun(@plus, B, hankel(A(1:L),A(L:end)))

results in

ans =
     6     6    10
     7     8    11
     9     9    12

Where rows contain the desired output vectors. Note that you can change @plus to @minus or any other user-defined function.




回答3:


You can create indices of a sliding window using hankel. Example:

a = [2 1 3];
b = [4 5 7 8 9];

idx = hankel(1:numel(a), numel(a):numel(b));
c = bsxfun(@plus, b(idx.'), a);

The result:

>> c
c =
     6     6    10   % [2 1 3] + [4 5 7]
     7     8    11   % [2 1 3] + [5 7 8]
     9     9    12   % [2 1 3] + [7 8 9]

(Note: This assumes b is longer than a, swap them if otherwise).




回答4:


I think you should do the following, assuming row arrays of doubles:

lenList(1) = length(list1);
lenList(2) = length(list2);


% find minumum length
[minLen, idx]   = min(lenList);

% find length difference
lenDiff    = abs(diff(lenList));

% initialize result
result     = zeros(lenDiff + 1, minLen);

% Check which list is the longest
if idx == 1
    shortList = list1;
    longList = list2;
else
    shortList = list2;
    longList = list1;
end

% Perform math
for ii = 1:(lenDiff + 1)
    result(ii, :) = shortList + longList(ii:(ii+minLen-1))
end


来源:https://stackoverflow.com/questions/26354656/comparison-and-shifting-strings-arrays-with-different-length-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!