How do I take a normal script with a function and turn it into a script with an anonymus function?
Mostrar comentarios más antiguos
I am trying to use this old script I wrote and turn it into an anonymous function script using a loop. I am having some issues though, and I think I have just not refined ever variable and function to operate the way I need it to.
Here is the script I have worked on so far to change to anonymous:
if true
%
% Clear Window, Variables, and Figure
clear;
clc;
clf;
% Variables
time_interval = 0.04; % seconds
tVals = (-5:time_interval:1); % -5 to 1 in steps of 0.04
% Equation
y = @(t) t.^2+3.*t+4;
% Making a for loop
for k = 1:length(tVals)
yVals = y(tVals(k)); % t will take on the values of tVals
% Plot the result
plot(tVals(k),yVals,'-r'); % Plots t-values vs y-values; in default color (blue)
% Label the Graph
xlabel('Time (seconds)'); % Labels x-axis
ylabel('Distance (meters)'); % Labels y-axis
title('Time vs. Distance'); % Titles the graph
end
% Find min/max value of y and time when it occurs
[ymax, t1] = max(yVals);
[ymin, t2] = min(yVals);
% Print Part a
fprintf('The max value of y is %.2f meters and occurs at t=%.1f seconds \n', ymax, tVals(t1));
fprintf('The min value of y is %.2f meters and occurs at t=%.1f seconds \n', ymin, tVals(t2));
end
And here is the old script:
if true
%
% Clear Window, Variables, and Figure
clear;
clc;
clf;
% Variables
time_interval = 0.04; % seconds
t = [-5:time_interval:1]; % -5 to 1 in steps of 0.04
% Equation
y = t.^2+3.*t+4;
% Plot the result
plot(t,y); % Plots t-values vs y-values; in default color (blue)
% Label the Graph
xlabel('Time (seconds)'); % Labels x-axis
ylabel('Distance (meters)'); % Labels y-axis
title('Time vs. Distance'); % Titles the graph
% Find min/max value of y and time when it occurs
[ymax, t1] = max(y);
[ymin, t2] = min(y);
% Print Part a
fprintf('The max value of y is %.2f meters and occurs at t=%.1f seconds \n', ymax, t(t1));
fprintf('The min value of y is %.2f meters and occurs at t=%.1f seconds \n', ymin, t(t2));
end
The old function returns fine giving me the proper plot and min and max values, but the new script does not bring up the plot and returns the min and max values as the same numbers.
Any advice or help would be greatly appreciated.
Thank you.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Creating, Deleting, and Querying Graphics Objects en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!