How do i save each loop of data within a loop so i can plot it.

조회 수: 1 (최근 30일)
Christopher Lee
Christopher Lee 2015년 10월 27일
답변: Sudhanshu Bhatt 2015년 10월 29일
This Code takes data from an excel sheet which contains two columns. The first column is the magnitude and the second is the direction of the vector. The code displays each x and y point but the variable 'x' and 'y' only save as the last calculated. What i need is to essentially take the excel data and graph the vectors.
heres the code:
clc
C=xlsread('homework16');
N=size(C,1);
i=1;
x=0;
y=0;
while i<=N
arrb(i,1)=C(i,1).*cosd(C(i,2));
arrb(i,2)=C(i,1).*sind(C(i,2));
i=1+i;
end
i=1;
while i<=N;
x=x+arrb(i,1);
y=y+arrb(i,2);
i=1+i;
end

답변 (2개)

Nick Hobbs
Nick Hobbs 2015년 10월 29일
I understand you would like to make sure the variable is saved during the loop. The issue looks like it may be due to variable scope. The following link will describe how to check variable scope in the editor and may help to resolve the issue.

Sudhanshu Bhatt
Sudhanshu Bhatt 2015년 10월 29일
Hi Christopher Lee,
As Nick has commented above the link will help you to better understand the scope of variables inside your code.
For example, you can save every computed value for X and Y by making them vectors and appending data to the vector after every iteration.
Demo code:
% Demo vectors to add to X and Y
a = [1,2,3,4,5,6,7,8];
b = [1,2,3,4,5,6,7,8];
% Declare X and Y as vectors
x = [0];
y = [0];
%Run for loop and save value inside X and Y in every iteration
if(length(a) == length(b))
for i = 1:length(a)
x = [x (x(i) + a(i))];
y = [y (y(i) + a(i))];
end
end
Thanks
Sudhanshu Bhatt

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by