MATLAB: Value assignment to vector, without loop

assignmentfor loop

Any possible ways (-fastest preferably) of doing the following without a for loop:
out = zeros(20,1)
value = [1 2 3 4]
frm = [4 9 14 16]
to = [4 12 14 17]
for i=1:length(frm)
out(frm(i):to(i)) = value(i)
end

Best Answer

Here's an option:
N = 20;
idx = (1:N)';
out = (idx >= frm & idx <= to)*value';
The indices in frm and to can't overlap, and out will have 0s wherever the values in value aren't placed.
Here's a similar method which doesn't use matrix multiplication:
N = 20;
out = zeros(N,1);
idx = (1:N)';
tf = idx >= frm & idx <= to;
out(any(tf,2)) = repelem(value, sum(tf));
No idea how these compare to other methods - including a for loop.