Trying to store values from a while into a 1D array and plot a graph with the values.

4 ビュー (過去 30 日間)
The following is my program so far:
% MATLAB M-file to solve a single equation using the Rearrangement method.
% The function is f(x)= cos^3(x) - x = 0 and the rearranged function % is g(x) = cos^-1(x^1/3).
clc % clear command window clear % clear workspace
k = 0; % Set the iteration number x = 0; % Set the starting value
diff = 1; % Set the difference between successive x values % to an arbitrary value to start the iteration
fprintf(' k xk\n') fprintf('%5i%10.4f\n', k, x) % output the starting value
while diff > 0.6e-4 % Continue until convergence is achieved to 5 decimal places
xlast = x;
x = 1/(cos(xlast^1/3)); % defines x(k+1) = g(x(k))
diff = abs(x - xlast); % Calculate the difference between two successive iterations
k = k + 1; % Add 1 to the iteration number
fprintf('%5i%10.4f\n', k, x) % Output the intermediate solutions to 6 decimal places
I am trying to modify this program such that it plots a graph of the iteration numbers against the x values, once covergence is acheived, by storing the x values in a 1D array.
Thanks in advance, fairly new to matlab.

回答 (1 件)

Jyotish Robin
Jyotish Robin 2017 年 1 月 16 日
Hi Maximillian,
Happy to hear that you are using MATLAB .
I understand that you would like to plot a graph of x-values against the iteration number. You could probably store the x-values in each iteration to an array (say, values) by including the following line in your code after the line which corresponds to incrementing k value :
Now, you can use the "stem" function to plot the "values" against the iteration number as follows:
Since you are new to MATLAB, I would recommend you to take a look at the documentation to know about the "stem" function:

Community Treasure Hunt

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

Start Hunting!

Translated by