Question
I have used a code that was written in someone elses previous question, that adds together all values over 0, after each zero. So if you had : [0 0 0 2 3 4 0 0 0 5 2 1], you would get [9 8] However, what i would want is this [ 0 0 0 0 0 9 0 0 0 0 0 8] So basically replacing the "open" spaces with a 0 Anyone know how i can achieve this?
Expert Answer
Neeta Dsouza
PhD Expert
Answered Aug 15, 2026
hello
try this :
T = [0 0 0 2 3 4 0 0 0 5 2 1]; % input data
T_out = zeros(size(T));
% find start and end indexes of groups of zeroes
id_nonzero = (T>eps);
[begin,ends] = find_start_end_group(id_nonzero);
% loop over this groupes
for k = 1:numel(begin)
start = begin(k); % start index of k th groups of non zero values
stop = ends(k); % end index of k th groups of non zero values
T_out(stop) = sum(T(start:stop));
end
T
T = 1×12
0 0 0 2 3 4 0 0 0 5 2 1
T_out
T_out = 1×12
0 0 0 0 0 9 0 0 0 0 0 8
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [begin,ends] = find_start_end_group(ind)
% This locates the beginning /ending points of data groups
% Important : ind must be a LOGICAL array
D = diff([0;ind(:);0]);
begin = find(D == 1);
ends = find(D == -1) - 1;
end
100% Run Guarantee
3-Hour Fast-Track Delivery
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here
Related matrix Questions & Solutions
Browse All →
Explore similar technical troubleshooting questions and verified MATLAB solutions:
Ready-to-Run MATLAB & Simulink Projects
Browse All Projects →