MATLAB: How to divide an array into separate arrays when the division concerns a proportion of the cell

arrayMATLAB

Hello,
I have a flow passing through a trough of 24.5 mm. The trough is divided into nb = 10 number of virtual streams (so the length of each virtual stream is Lb = 2.45 mm). The flowrate within each virtual stream is also known. The flow at the end of the trough is divided into n number of flows by n1 number of cutters. n might vary in different applications. The cutters position x across the trough might also vary. I need to simulate the cutters actions by calculating the proportion of the flow directing to each separate flow. The below figure shows the concept. The below array is the trough of 10 virtual streams and the digits in each cell shows the flowrate. The red sections show the width of the separated flows at the end of the trough. For instance, the first left flow contains the first plus ¾ of the second virtual streams and so on.
I tried to write the below code to calculate each separate flow and it works, but I am searching a more intelligent generic code. I was wondering if you could help me improve it.
clc;
clear;
close all;
D = [1.1 1.2 1.4 1.7 2.0 2.3 2.7 3.1 3.6 4.2];
nb = 10;
Lb = 2.45;
x = [0;4;7;11;16;24.5];
L = x(2:end)-x(1:end-1);
n = floor(L ./ Lb); % Number of virtual streams that report completely to a separate flow
p = (L(1:end-1) - n(1:end-1) .* Lb) ./ Lb; % Proportion of the virtual stream that PARTIALLY reports to a separate flow
z(1,:) = [ones(1,n(1)), p(1), zeros(1,nb-n(1)-1)];
z(2,:) = [zeros(1,n(1)) 1-p(1) ones(1,n(2)), p(2), zeros(1,nb-n(1)-n(2)-2)];
z(3,:) = [zeros(1,n(1)+n(2)+ceil(p(1)+p(2))) 1-p(2) ones(1,n(3)), p(3), zeros(1,nb-n(1)-n(2)-n(3)-3)];
z(4,:) = [zeros(1,n(1)+n(2)+n(3)+ceil(p(1)+p(2)+p(3))) 1-p(3) ones(1,n(4)), p(4), zeros(1,nb-n(1)-n(2)-n(3)-n(4)-4)];
f = z .* repmat(D,length (L(1:end-1)),1);
f(5,:) = D - sum(f);
F = sum(f,2);

Best Answer

% data:
D = [1.1,1.2,1.4,1.7,2.0,2.3,2.7,3.1,3.6,4.2];
nb = 10;
Lb = 2.45;
x = [0;4;7;11;16;24.5];
% code:
Lw = linspace(0,24.5,nb+1) % stream edges
ida = x(1:end-1)<=Lw(2:end) & x(2:end)>=Lw(1:end-1) % any
idl = x(1:end-1)>Lw(1:end-1) & x(1:end-1)<Lw(2:end) % left
idr = x(2:end)>Lw(1:end-1) & x(2:end)<Lw(2:end) % right
K2 = ida + idr.*(x(2:end)-Lw(2:end))./Lb + idl.*(Lw(1:end-1)-x(1:end-1))./Lb % scale
F2 = sum(D.*K2,2)
Giving:
F2 =
1.8592
1.6408
2.8796
4.7531
12.1673
This code requires MATLAB >=R2016b, for earlier versions use bsxfun where required.