How to add together values in matrix and replace the empty spaces with zeroes

Illustration
Elias Huse - 2023-04-20T11:34:13+00:00
Question: How to add together values in matrix and replace the empty spaces with zeroes

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

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

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

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!