a=[1 2 3];
for ii=1:sum(a)
disp("Hello")
end
1:a(1,1:size(a,2)) == 1:a(1,[1 2 3]) == 1:a(1,1) == 1:1 == 1
actually creates an array containing the number 1
(more specific: a(1)
, as 1:[1 2 3]
will evaluate to 1:1
, discarding all elements further on in the vector). Given the number 6 you mention I take it you want the sum of all elements in a
which is given by sum
.
Final word of caution: please refrain from using i
and j
as variable names, as they also denote the imaginary unit.
Reading your comment you probably need a nested loop, as the entries of a
might not be monotonically increasing:
k = 1; % counter to show which iteration you're in
for ii = 1:numel(a) % for all elements of a do
for jj = 1:a(ii) % do the following a(ii) times
disp('Iteration %d', k)
disp('Hello')
k = k+1; % increase iteration count
end
end
Note that both methods fail (obviously) when a
does not contain strictly non-negative integer values.