summing between array with different length
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
BhaTTa
2024-10-21
编辑:BhaTTa
2024-10-21
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!