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 view (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 26 Mar 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 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!