2

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

Amro
  • 123,847
  • 25
  • 243
  • 454
Cina
  • 9,759
  • 4
  • 20
  • 36

4 Answers4

4

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.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
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
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
1

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).

Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454
0

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
Nick
  • 3,143
  • 20
  • 34