Save loop data in vector

懵懂的女人 提交于 2019-12-02 21:04:08

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/23913491/save-loop-data-in-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!