Guardar datos de bucle en vector

when I run my script, all the values are displayed, but I want all the values in vector, so what can I do?

x=[1 2 3 4 5];
y=[1 2 3 4 5];

xx=[1.2 1.6 1.8 2.4 2.8 3.4 4.9 2.6];
yy=[1.2 1.6 1.8 2.5 2.8 3.3 4.9 2.5];

plot(x,y,'.g',xx,yy,'*b')

for j=1:length(xx) 

    if xx(j)<x(1)
        value=0    
    elseif xx(j) >x(1) & xx(j)<x(2)
        value=1
    elseif xx(j) >x(2) & xx(j)<x(3)
        value=2 
    elseif xx(j) >x(3) & xx(j)<x(4)
        value=3
    elseif xx(j) >x(4) & xx(j)<x(5)
        value=4
    elseif xx(j) >x(5) & xx(j)<x(6)
        value=5
    else
        value= NaN
    end
end

preguntado el 28 de mayo de 14 a las 14:05

Utilice la herramienta value(j)=some_value and try to avoid using i or j as iterators. Also, consider pre-allocation with value = zeros(length(xx),1). And also, consider using numel en lugar de length. -

Thanks, but i have 8 answers again, i can i put all of them in the same vector, and the answers are not correct =/ -

You want a vector as the result right? Print value después de que termine el bucle. -

2 Respuestas

This is a relatively simple answer, you need to create an array to store your data in. I simply add the line value = zeros(1,length(xx)). This creates a pre-allocated array of 0's which is then overwritten in the loop (value(jj) = ##) to save the values.

x=[1 2 3 4 5];
y=[1 2 3 4 5];
xx=[1.2 1.6 1.8 2.4 2.8 3.4 4.9 2.6];
yy=[1.2 1.6 1.8 2.5 2.8 3.3 4.9 2.5];
plot(x,y,'.g',xx,yy,'*b')
value = zeros(1,length(xx));
for jj=1:length(xx) 
    if xx(jj)<x(1)
        value(jj)=0;
    elseif xx(jj) > x(1) && xx(jj) < x(2)
        value(jj)=1;
    elseif xx(jj) > x(2) && xx(jj) < x(3)
        value(jj)=2;
    elseif xx(jj) > x(3) && xx(jj) < x(4)
        value(jj)=3;
    elseif xx(jj) > x(4) && xx(jj) < x(5)
        value(jj)=4;
    elseif xx(jj) > x(5) && xx(jj) < x(6)
        value(jj)=5;
    else
        value(jj)= NaN;
    end
end

contestado el 28 de mayo de 14 a las 14:05

YES! is exactly this! Thank you very much! =) - user3683409

@user3683409 You should then consider upvoting/accepting the answer - luis mendo

@LuisMendo sorry, but is my first time here! But thanks for the advice! =) - user3683409

@user3683409 No worries! - luis mendo

You will need to create an array before the for loop, initialized with zeros like this:

value = zeros(1,length(xx));

This vector will be updated inside the loop. Initializing it with zeros will guarantee that it won't need memory allocation for each iteration. Its size is the same number of iterations of the loop, as this is the final number of values you use.

And then, after each value inside the loop, write a (j). This will save the current value to the current position in the value vector in each iteration;

After the loop, write value, and it will print value as a vector.

contestado el 28 de mayo de 14 a las 15:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.