Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create strings from the indices of two vectors in Matlab

Tags:

arrays

matlab

I have two vectors a and b as an example:

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

I want to create strings from the indices of a and b:

c1 = a(1):b(1) = [1 2 3 4 5];
c2 = a(2):b(2) = [2 3 4 5 6];
c3 = a(3):b(3) = [3 4 5 6 7];
c4 = a(4):b(4) = [4 5 6 7 8]; 

Then I want to concatenate the obtained strings:

C = cat(2, c1, c2, c3, c4) = [1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8];

I would like a general solution to help me automatize this algorithm.

like image 413
Bowecho Avatar asked Aug 21 '15 11:08

Bowecho


2 Answers

Solution

This should do the trick without using a loop:

>> a = [1 3 4 5];
>> b = [5 6 7 8];
>> resultstr = num2str(cell2mat(arrayfun(@(x,y) x:y,a,b,'UniformOutput',false)))

resultstr =

1  2  3  4  5  3  4  5  6  4  5  6  7  5  6  7  8

Performance

I tried to do a quick comparison between this method, Luis Mendo's method and the for loop (see e.g. A. Visser's answer). I created two arrays with pseudo-random numbers from 1 to 50 and 501 to 1000 and timed the calculation for array sizes from 1 to 300, disregarding the string conversion.

Performance comparison

Luis Mendo's anwer is the clear winner, in terms of time complexity arrayfun seems to be on par with bsxfun. The for loop fares much worse, except for very small array sizes, but I'm not sure the timing can be trusted there.

The code can be found here. I'd be very happy to get some feedback, I'm a bit unsure about those measurements.

like image 94
dasdingonesin Avatar answered Sep 30 '22 11:09

dasdingonesin


This can be done without loops (be they for, arrayfun or cellfun) using bsxfun's masking capability. This works also if the "strings" have different lengths, as in the following example.

a = [1 2 3];
b = [3 5 6];
m = (0:max(b-a)).'; %'
C = bsxfun(@plus, a, m);
mask = bsxfun(@le, m, b-a);
C = C(mask).';

The result in this example is:

C =
     1     2     3     2     3     4     5     3     4     5     6
like image 36
Luis Mendo Avatar answered Sep 30 '22 12:09

Luis Mendo