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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With