An easy way for adding on pervious row that expands

1 次查看(过去 30 天)
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
Davide Masiello 2022-3-7
编辑:Davide Masiello 2022-3-7
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 个)

Max Alger-Meyer
Max Alger-Meyer 2022-3-7
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

类别

Help CenterFile Exchange 中查找有关 Mathematics and Optimization 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by