Using nested FOR() loops to populate a matrix
Ältere Kommentare anzeigen
Hello,
Having previously populated a matrix to demonstrated the MacLaurin Series, but entering all the data essentially manually, I'm having a go at using FOR() loops to do the same job again.
I'm trying to demonstrate how the MacLaurin series progressively and more accurately approximates e^x, by creating a vector series of X values from 0 to 1 in steps of 0.01 and then 25 Y series in a single matrix, each row being a progressively better approximation, i.e. row 1 being f(x)=f(0).x^0.1/0!, row 2 being f(x)=f(0).x^0*1/0! + f(0).x^1*1/1!, row 3 being f(x)=f(0).x^0*1/0! + f(0).x^1*1/1! + f(0).x^2*1/2! etc...
Here's my attempt at the code so far:
% MacLaurin Series of e^x
format longG
% define vector to hold series x values
X = 0 : 0.01 : 1;
% Create matrix to contain the results of each function in the series
% A FOR loop is used to populate the matrix without having to write out all
% the series iterations manually
for i = 0:25
F(i+1,:) = [(X(1,:).^i)/factorial(i)]
end
% Create increasingly better approximations by summing increasing numbers
% of function results
for i = 1:26
for j = 1:i
Y(i,:) = [Y(i,:) + F(j,:)]
end
end
I'm pretty sure vector F is created correctly, but trying the same method with matrix Y results in the error:
Unrecognized function or variable 'Y'.
Error in tutorial_6d (line 21)
Y(i,:) = [Y(i,:) + F(j,:)]
The more I think about the error, though, the less certain I am that the entire concept of what I'm trying to do is correct...
If anybody has the time to help me wit the logic of this, I'd be very grateful,
Thanks,
Paul
2 Kommentare
Note that none of those square brackets do anything, so you might as well get rid of them. Why did you add them?
By the way, here is the very simple MATLAB approach without loops:
format longG
X = 0:0.01:1;
I = (0:25).';
F = (X.^I)./factorial(I);
Y = cumsum(F,1)
paul
am 26 Sep. 2022
Akzeptierte Antwort
Weitere Antworten (1)
John D'Errico
am 26 Sep. 2022
Bearbeitet: John D'Errico
am 26 Sep. 2022
You have a solution. It works. Do you need for loops, or worse, nested for loops? Of course not. The entire point of this answer is to show that you don't need to use loops to solve a problem like this. Use MATLAB as it was designed to be used.
Nmax = 10; % maximum number of terms in the expansion
Nx = 20; % number of points to be sampled in [0,1]
N = 0:Nmax; % explicitly a row vector
X = linspace(0,1,Nx)'; % see that A is explicitly a column vector
M = X.^N./factorial(0:Nmax); % % using .^ and ,/ to expand the vectors automatically
M = cumsum(M,2); % accumulation, instead of a loop
err = M - exp(X); % the error of approximation
Note that several of the lines above require R2016b or later to operate correctly, but by now, most people should have that much.
[XX,NN] = meshgrid(X,N);
surf(X,N,err')
xlabel X
ylabel N
zlabel 'error of approximation'
Next, looking at the error in terms of a logged z-axis so we can better see the behavior near zero...
surf(X,N,abs(err'));
xlabel X
ylabel 'Number of terms'
zlabel 'Absolute error'
set(gca,'zscale','log')
So as expected, the error is maximal near x==1. As x grows larger, you need more terms in the Taylor series.
Near x==0 we see almost full double precision accuracy for only or one or two terms. Again, this is expected. You need more terms as x moves away from zero.
4 Kommentare
Stephen23
am 26 Sep. 2022
"coming from a programming background, it seemed intuitive"
The name MATLAB comes from MATrix LABoratory. While FOR/WHILE loops are certainly useful, the simple and intuitive way to solve many problems in MATLAB is to work with entire matrices (vectors/arrays) at once.
John D'Errico
am 27 Sep. 2022
Looping is A solution. In fact, it is often a good solution. As long as your code is not taking too much time to run, then all that matters is that you wrote it, and it works. Get on to solving the next problem, rather than optimize the curent one. :)
At the same time, the reason for writing this answer was to give you a target, something to shoot for. I want to teach you to write code that uses MATLAB efficiently, and that uses the capabilities of MATLAB. The goal is to get people so they automatically write code that only uses loops when that is the only solution.
paul
am 27 Sep. 2022
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

