summing between array with different length
3 views (last 30 days)
Show older comments
I have two arrays:
x = [ 1 2 3 4 5 6 7 8 9 0]; y = [ 6 7 8 9 ];
I'd like to add y in the middle of x so they form z
z = [1 2 3 10 12 14 16 8 9 0];
and second result (with shifting variable y) be
z = [1 2 3 4 11 13 15 17 8 0];
How would I go about doing this?
0 Comments
Answers (1)
BhaTTa
on 21 Oct 2024
Edited: BhaTTa
on 21 Oct 2024
Hey @Moch Arief Albachrony, I assume that at first step you want to add elements of array y to elements of array x starting at index 4 till index 7 and in next step you want to shift the index by 1 and add them. Below I have provided the code to achieve it:
% Define the arrays
x = [1 2 3 4 5 6 7 8 9 0];
y = [6 7 8 9];
Idx = 4;
z1 = x; % Copy x to z1
z1(Idx:Idx+length(y)-1) = x(Idx:Idx+length(y)-1) + y;
% Second result: Insert y shifted by one position to the right
z2 = x; % Copy x to z2
z2(Idx+1:Idx+length(y)) = x(Idx+1:Idx+length(y)) + y;
% Display the results
disp('First result:');
disp(z1);
disp('Second result:');
disp(z2);
Hope it helps.
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!