MATLAB Answers

Add particular elements of array

조회 수: 1(최근 30일)
Awais Saeed
Awais Saeed 2021년 8월 1일
댓글: Rik 2021년 8월 1일
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

채택된 답변

Rik
Rik 2021년 8월 1일
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
ans = 2×7
-Inf -Inf -Inf -Inf 4 5 6 NaN NaN NaN 4 NaN NaN NaN
ans = 2×7
-Inf -Inf -Inf -Inf -Inf 1 2 NaN NaN NaN 4 4 NaN NaN
ans = 2×7
-Inf -Inf -Inf -Inf -Inf 1 2 NaN NaN NaN 4 4 NaN 2
k_new=c2(~isnan(c2))
k_new = 1×3
4 4 2
  댓글 수: 2
Rik
Rik 2021년 8월 1일
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.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by