Add particular elements of array
1 view (last 30 days)
Show older comments
Let's say that k is a vector and
k = [1 1 1 1 4 1 1];
k could be anything I just assumed [1 1 1 1 4 1 1]. Let's say there is a variable
limiter = 3;
I want to add elements of k that are less than or equal to the variable 'limiter' and put it in a new vector, let's say k_new. For example, k(1),k(2),k(3),k(4) <= limiter, add them and put it in k_new resulting
k_new = [4];
Now k(5) is greater than limiter, it should be ignored and should be stored in k_new as it is, resulting
k_new = [4 4];
the final desired vector is
k_new = [4 4 2]
I worte a program using two while loops and somehow the loop keeps running. I want to do this using a single while loop if possible and I need help in doing that. Below is my code
limiter = 3;
k = [1 1 1 1 4 1 1];
run1 = true;
while (run1)
ii = 1;
jj = 1;
run2 = true;
while (run2)
if (k(ii) < limiter)
k_new(jj) = k(ii)+k(ii+1)
ii = ii + 2; % increment of 2 because we need
% to check k(ii+2) as k(ii) and k(ii+1) have been checked
else
k_new(jj) = k(ii)
ii = ii + 1;
end
jj = jj + 1;
if (ii == length(k))
k_new(jj) = k(ii)
break
end
if (ii > length(k))
run2 = false;
end
end
k = k_new
clear k_new
if (find(k==min(k),1,'last') == length(3)) % Stop the outer while loop
run1 = false;
break
end
end
0 Comments
Accepted Answer
Rik
on 1 Aug 2021
Not the tidiest code, but it all happens in a single loop, with cumsum doing the addition prior to the loop.
%set your data
data=[1 1 1 1 4 1 1];
limiter=3;
%add all elements together
c1=cumsum(data);c2=NaN(size(c1));
%c1 will hold the corrected cummulative sums (masked with -inf)
%c2 will contain the end result (masked with NaNs)
while true
ind=find(c1>limiter,1);
if isempty(ind)
%break loop
if isnan(c2(end)),c2(end)=c1(end);end
[c1;c2]
break
end
c1((ind+1):end)=c1((ind+1):end)-c1(ind);
c2(ind)=c1(ind);
c1(1:ind)=-inf;
[c1;c2]
end
k_new=c2(~isnan(c2))
2 Comments
Rik
on 1 Aug 2021
I don't think I completely understand what you mean, but it probably would not be too hard to modify this code. I would encourage you to try it yourself.
More Answers (0)
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!