Reputation: 63
Let's say we have a "Dirac comb" which gives the beginning positions of some "pattern":
N_pattern = 5; pattern = rand(1,N_pattern);
N = 100; dirac_comb = zeros(1, N);
idx = [1 20 50 80]; % let's say we want four occurrences of the pattern inside the final_vector
dirac_comb (idx) = 1; % let's say this the comb with the positions of patterns
All I want to do is to insert the "pattern" vector on the positions indicated by the Dirac comb. Normally, this may be done by a convolution:
final_vector = conv(dirac_comb, pattern);
I don't want to use the convolution because I use very large vectors and thus it is very slow. The presence of the Dirac comb in this problem is a little bit forced, the idx
variable might be enough to solve this problem.
First question: how to insert the "pattern" in the final_vect
at the positions indicated by idx
, in a vectorized way.
Second question: let's say we randomized the positions idx
of the patterns, so there is a possibility that two patterns may intersect. If this would happen, I have to sum up these two patterns (the region of intersection).
idx = randi([1 N-N_pattern],[1, 8]); % lets' say we have 8 occurrences
Should it be possible to take into account this summation, yet in a vectorized manner?
Upvotes: 0
Views: 98
Reputation: 6187
To insert the pattern into final_vector
without using conv()
you can use replication and indexing in MATLAB.
First you'll need to augment idx
so that instead of it containing the starting elements of the ranges where it should place pattern
it contains all of the indices. We can accomplish this using bsxfun()
(as pointed out by @Andras Deak)
>> idx = [1 20 50 80];
>> indexes = bsxfun(@plus,idx',0:N_pattern-1)
indexes =
1 2 3 4 5
20 21 22 23 24
50 51 52 53 54
80 81 82 83 84
then you can insert pattern
into final_vector
by indexing the vector with idx
and replicating pattern
with either repmat()
or bsxfun()
(again pointed out by @Andras Deak) to fit in those indexes
>> final_vector = zeros(1, length(dirac_comb) + length(pattern) - 1);
>> final_vector(indexes) = repmat(pattern, size(indexes, 1), 1);
or
>> final_vector = zeros(1, length(dirac_comb) + length(pattern) - 1);
>> final_vector(indexes) = bsxfun(@plus, pattern, zeros(numel(idx), 1));
Just a point to note which I didn't think previously needed mentioning. conv()
produces a vector of length length(dirac_comb) + length(pattern) - 1
. To produce the same length as conv()
final_vector
should be allocated with final_vector = zeros(1, length(dirac_comb) + length(pattern) - 1);
.
Upvotes: 1