# An easy way for adding on pervious row that expands

1 view (last 30 days)
Yaser Khojah on 7 Mar 2022
Commented: Yaser Khojah on 8 Mar 2022
I have two questions that are brought from my codes where I need to perform to jobs as below. Is there an easy approach as I have large data.
Thanks for the help!
% First part
x1 = [100; 200; 50; 100];
Muliple = 0.1;
x1(1) .* Muliple = 10; % this will be sent to the following row
(x1(2) - 10) .* Muliple = 19; % this will be sent while adding the previous row (10 + 19)
(x1(3) - (10 + 19)) .* Muliple = 2.1; % (
(x1(4) - (10 + 19 + 2.1)) .* Muliple = 21.1;
% Second part
%Another Part I need help please how to divide x1 by 2 and send each half to the following row while adding
%for example
x2= [50; 50 + 100; 100 + 25; 25 + 50; 50];

Davide Masiello on 7 Mar 2022
Edited: Davide Masiello on 7 Mar 2022
x = [100; 200; 50; 100];
Muliple = 0.1;
x1 = zeros(size(x));
x1(1) = x(1)*Muliple;
for i = 2:length(x)
x1(i) = (x(i)- sum(x1(1:i-1)))*Muliple;
end
x2 = [x/2;0]+[0;x/2];
This yields
x1 =
10.0000
19.0000
2.1000
6.8900
x2 =
50
150
125
75
50
##### 1 CommentShowHide None
Yaser Khojah on 8 Mar 2022
Thanks so much for the code. :)

### More Answers (1)

Max Alger-Meyer on 7 Mar 2022
First part (note that this follows the algorithm you described but the fourth that you listed for the first part is wrong):
x1 = [100; 200; 50; 100];
Multiple = 0.1;
x2 = zeros(size(x1));
for i = 1:numel(x2)
if i > 1
x2(i) = (x1(i)-sum(x2(1:(i-1))))*Multiple;
else
x2(i) = x1(i)*Multiple;
end
end
x2
x2 = 4×1
10.0000 19.0000 2.1000 6.8900
Second Part:
x2 = (x1)/2;
x3 = x2;
for i = 1:numel(x2)
if i > 1
x3(i) = x2(i) + x2(i-1);
end
end
x3(end+1) = x2(end);
x3
x3 = 5×1
50 150 125 75 50
##### 1 CommentShowHide None
Yaser Khojah on 8 Mar 2022
Thanks so much for the code. It works :)