1
votes

The first vector (M) has 96 elements and second one (L) has 24. The first is information in every 15mn and the second is information every hour. What I want is to multiply the first four elements in M with the first element in L, to end up with only one vector with 96 elements, like so -

enter image description here

Is there an easy way to do this without making the code too complex?

3
If you just multiply you still have 4 values per hour, so what exactly do you want? - flawr
For that example numbers, what would be the first two numbers of the result? From your description I would expect a 96 element output, how is it accumulated to 24 elements? - Daniel
@Daniel I'm sorry, my mistake, I meant 96 elements output - jonas345

3 Answers

0
votes

You can reshape the array,

a = [2,4,6,8];
b = 1:16;
c = repmat(a,4,1);
d = reshape(a,1,4*length(a));
e = b.*d;

note that in case you want a oneliner these can be combined

b.*reshape(repmat(a,4,1), 1, 4*length(a));

I cannot say whether this is faster than the other options, but it should not be a very large difference. Choose this in case you think it is more comprehensive.

6
votes

You are looking for broadcasting, so let bsxfun help you out -

reshape(bsxfun(@times,reshape(M,4,[]),L(:).'),1,[])
4
votes

Using the kron function you can easily generate the indices for L, it creates [1,1,1,1,2,2,2,2....]

L(kron(1:numel(L),ones(1,4))).*M

In case you have trouble understanding kron, the same can be achieved using ceil:

L(ceil([1:numel(M)]/4)).*M