Filter löschen
Filter löschen

How I can fix my problem when I add a function to the main script within for loop and run iteration was made with an error?

1 Ansicht (letzte 30 Tage)
Hello! Kindly ask help in function and running through main script
I wanted to combine all. I have one function which is 'planeLocation7' and going to call it in the main script with a loop.
function [XBar, YBar, ZBar, p, Xr, Yr, Zr, ThetaBar, PhiBar, Rr] = planeLocation7(X0, Y0, Z0, Theta0, Phi0)
When I am running through the main script code makes for loop but shows me only one result for k=1, and for the other k shows 0, NaN, etc. Seems like I made mistake with inputs and zeros(1:k).
In planeLocation7 I calculate all data and then Xr, Yr, Zr, TheBar, PhiBar will be considered as X0, Y0, Z0, Theta0, Phi0 for the next iteration. Before I had two functions and the main, and it worked, but after I added a formula to calculate XBar, YBar, ZBar to the 'planeLocation7' function the main script does not work properly. Kindly ask for help
here is my main script.
clc
clear all
close all
X0 = 1.5;
Y0 = 1.5;
Z0 = 3.0;
Theta0 = 30;
Phi0 = 90;
K = 5;
X = [X0 zeros(1,K)];
Y = [Y0 zeros(1,K)];
Z = [Z0 zeros(1,K)];
Theta = [Theta0 zeros(1,K)];
Phi = [Phi0 zeros(1,K)];
for i = 1:K
i
X = [X0 zeros(1,K)];
Y = [Y0 zeros(1,K)];
Z = [Z0 zeros(1,K)];
Theta = [Theta0 zeros(1,K)];
Phi = [Phi0 zeros(1,K)];
[XBar, YBar, ZBar, p, Xr, Yr, Zr, ThetaBar, PhiBar, Rr] = planeLocation7(X(i), Y(i), Z(i),Theta(i), Phi(i));
X(i+1) = Xr;
Y(i+1) = Yr;
Z(i+1) = Zr;
Theta(i+1) = ThetaBar;
Phi(i+1) = PhiBar;
end
fprintf('X(%d)=%f\n', i, X(i));
fprintf('Y(%d)=%f\n', i, Y(i));
fprintf('Z(%d)=%f\n', i, Z(i));
fprintf('Theta(%d)=%f\n', i, Theta(i));
fprintf('Phi(%d)=%f\n', i, Phi(i));
disp("===");
Thank you in advance for your consideration

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 26 Mär. 2023
for i = 1:K
i
X = [X0 zeros(1,K)];
You overwrite all of X each iteration of for i
X(i+1) = Xr;
You overwrite one element of X near the end of the loop. But the next iteration, you overwrite all of X, so the stored value will be lost -- except on the very last iteration.
  3 Kommentare

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by