Increment components of vector till a desired limit
3 views (last 30 days)
Show older comments
Hello everyone, I need to increment the components of a column vector in the form of A= [1 2 3 4 5] till every component hits 100.
For example, the first iteration should be A = [1 2 3 4 5 2 3 4 5 6] and the third one A = [1 2 3 4 5 2 3 4 5 6 3 4 5 6 7] and so on till each of the originary 4 components gets to 100; so not only the vector components needs to grow in magnitude, but the actual number of vector components need to grow too. I'm pretty sure that this can be done with a while loop but I'm getting stuck on the syntax.
Thanks in advance to everybody.
clear all
clc
A= [1; 2; 3; 4; 5; 6; 7; 8; 9; 10];
while (i) < 100
A= A+1
i= i+1
end
0 Comments
Accepted Answer
Jan
on 9 Jan 2021
Edited: Jan
on 9 Jan 2021
You know in advance how many iterations are needed: The smallest element must be increased until it is 100.
A = [1 2 3 4 5];
Limit = 100;
Iter = Limit - min(A);
Result = A(:) + (0:Iter); % As matrix, Auto-expanding needs >= R2016b
Result = Result(:).'; % As row vector
Alternative:
Result = repmat(A, 1, Iter + 1) + repelem(0:Iter, 1, numel(A));
Or if you want a loop:
nA = numel(A);
Result = zeros(1, nA * (Iter + 1)); % Pre-allocate
index = 0;
for k = 0:Iter
Result(index + 1:index + nA) = A + k;
index = index + nA;
end
0 Comments
More Answers (2)
Image Analyst
on 8 Jan 2021
Edited: Image Analyst
on 8 Jan 2021
Use any():
A= [1; 2; 3; 4; 5; 6; 7; 8; 9; 10];
thisA = A(end-3:end);
maxIterations = 1000; % Set up a failsafe to prevent an infinite loop
loopCounter = 1;
while any(thisA < 100) && loopCounter < maxIterations
thisA = A(end-3:end) + 1;
A = [A; thisA];
loopCounter = loopCounter + 1;
end
A
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!