Trying to get all results from a for loop into an array

1 Ansicht (letzte 30 Tage)
Ted Baker
Ted Baker am 29 Jul. 2020
Kommentiert: Ted Baker am 31 Jul. 2020
I researched how others did it on this forum, but what I could get to work fills the first cell of the array with []. I am just wondering how to try and get the starting position into the first cell. It could also have something to do with the if function .... I don't know enough to try and help!
Any advice on making my code neater would be amazing as well, I am very new to all of this!
The stuff in bold is inside my for loop, and is the bit that I am trying to get to work.
clc
clear
close all
format long G
% Given variables
xpos = 4.000; % Initial x position
ypos = 0.000; % Initial y position
t = [0.00,0.04,0.08,0.12];
xvel = [0.0000,-0.2478,-0.4943,-0.7384]; % x velocities
yvel = [4.0000, 3.9915, 3.9659, 3.9234]; % y velocities
count = 0;
% Find the position of x and y using the velocities
for a = 1:length(t)
count = count + 1 ;
if count-1 <= 0
continue
end
xpos = xvel(count).*(t(count) - t(count-1)) + xpos ;
xposa{a} = xpos;
ypos = yvel(count).*(t(count) - t(count-1)) + ypos ;
yposa{a} = ypos;
end
disp(xposa);
disp(yposa);
Thanks,
Ted Baker

Antworten (1)

KSSV
KSSV am 29 Jul. 2020
clc
clear
close all
format long G
% Given variables
xpos = 4.000; % Initial x position
ypos = 0.000; % Initial y position
t = [0.00,0.04,0.08,0.12];
xvel = [0.0000,-0.2478,-0.4943,-0.7384]; % x velocities
yvel = [4.0000, 3.9915, 3.9659, 3.9234]; % y velocities
% Find the position of x and y using the velocities
for a = 1:length(t)-1
xpos = xvel(a).*(t(a) - t(a+1)) + xpos ;
xposa{a} = xpos;
ypos = yvel(a).*(t(a) - t(a+1)) + ypos ;
yposa{a} = ypos;
end
disp(xposa);
disp(yposa);
  1 Kommentar
Ted Baker
Ted Baker am 31 Jul. 2020
Hey KSSV,
That didn't end up working as it gives me the wrong values. I tried changing it to
for a = 1:length(t)
xpos = xvel(a).*(t(a+1) - t(a)) + xpos ;
But then I came across the same issue apart from it did not give me the last value.
Thanks anyway.
Ted

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by