FOR loop count to the end but the length of the array is different
1 view (last 30 days)
Show older comments
I have a question and I think it's easy but I am bit confused..
I have to do a for loop starting from 3 until 7..the loop seems to count from 1 until 7... so the length of the vector is not correct and should be 5. Why can not get the length of 5 ??
x=[2 3 4 5 6 7 8 9 10 55 20];
Stephen23 on 25 Feb 2023
Edited: Stephen23 on 25 Feb 2023
"so there is no way to have the output vector with directly length of 5 ?"
Of course there are multiple ways to achieve this, here is probably the best one (based on the principal that in general it is easiest to loop over indices 1:N, rather than over some special values):
x = [2:10,55,20]
y = zeros(5,1);
v = 3:7;
for k = 1:numel(v) % this is usually better
y(k) = x(v(k)) + 3;
"I need to have the loop starting from 3"
I recommend avoiding doing that, but if you really must (hopefully not for reasons related to DIR):
y = zeros(5,1);
z = 0;
for k = 3:7
z = z+1;
y(z) = x(k)+3;
Of course using a loop is not very good use of MATLAB, better would be simply:
y = x(v).' + 3
"...after prelocation will be zeros and I do not wanna remove them with y (y==0) = any ideas ??"
I just showed you three approaches. Not hard at all.
More Answers (1)
Edited: dpb on 25 Feb 2023
Observe the following...
Note that MATLAB created the array of seven values and filled the last entry.
In your original loop, even though you created the initial y array to have 5 elements, you then addressed outside those bounds in the subsequent for...end loop and MATLAB obliged by creating those elements and extending the array to match.
MATLAB arrays are one-based and are always from 1:N elements; unlike Fortran for example that can have arbitrary array indexing, MATLAB is like the dog with one and only one trick in this regards.
It's simply not possible in MATLAB to have an array that is addressed from 3:7 that contains only 5 elements; the array will be as you see, from 1:7 but maybe only the last 5 have been filled with data other than the automagic preallocation by zero that MATLAB does invisibly.
You could use NaN as the indicator
x=[2 3 4 5 6 7 8 9 10 55 20]; % your original x vector
i1=3; i2=7; % the range you wanted to write over
y=nan(i2,1); % preallocate to nan to upper limit
y(i1:i2)=x(i1:i2)+3 % do the for loop equivalent MATLAB style
y=y(isfinite(y)) % now keep only the real values
The better way with MATLAB to avoid the last step and the need for the preallocation at all when the RHS of the assignment can be written in vector form would be to write
y=x(i1:i2)+3 % just write what is wanted to new variable
Note the default vector is a row; if the column vector is desired, either write the transpose on RHS expression or in the indexing vector
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!