Change the loop index variable inside the loop

I need to change the loop variable inside the iteration, since I need to access the elements of the array in the loop, which changes the wrt size inside the loop.

Here is my code snippet:

que=[];
que=[2,3,4];
global len;
len=size(que,2)
x=4;
for i=1:len 
    if x<=10
    que(x)= 5;
    len=size(que,2)
    x=x+1;

    end
end
que

The array should print as:

2 3 4 5 5 5 5 5 5 5 

But it is printed as follows:

2 3 4 5 5 5

In Visual C ++, an array is computed correctly, and the entire array of 10 elements is printed, which increases at runtime.

How can I accomplish this in matlab?

+5
source share
4 answers

You should use while while instead of for a loop to do this:

que = [2 3 4];
x = 4;
while x <= 10
  que(x) = 5;
  x = x+1;
end

:

que = [2 3 4];             %# Your initial vector
%# Option #1:
que = [que 5.*ones(1,7)];  %# Append seven fives to the end of que
%# Option #2:
que(4:10) = 5;             %# Expand que using indexing
+10

, while, ? MATLAB. , .

, , , .

que = [que,repmat(5,1,10 - length(que))];

, , , .

, len ?

+3

- , . for 3 - que, 5s . len , i for . , for , , len, , i 1 3.


x length(que)+1?

, = 5? 2 3 4 0 5 5 5 5 5 5? 2 3 4 5 5 5 5 5 5?

2 3 4 5 5 5 5 5 5 5? ( x)

matlab-ish @gnovice:

que = [2 3 4];  
x = 5;
y = 10;
val = 5;
que(x:y)=val;

@gnovice:

que = [2 3 4];
x = 5;
y = 10;
val = 5;
que = [que, val.*ones(1,y-x+1)];

que = [que, repmat(val, 1, y-x+1)];

@woodchips:

que = [que, repmat(val, 1, y - length(que))];

In your situation, using a loop (for or at that time) is really bad, because in each loop you increase the size of the vector que with memory redistribution.

0
source

Matlab software loops have terrible performance. Like everyone else, do it with the built-in Matlab functions and compute everything as much as possible. If you really need loop designs, perhaps C will be your best bet :)

0
source

All Articles