How to use an anonymous function in a ''for''?

2 Ansichten (letzte 30 Tage)
Migue Balma
Migue Balma am 15 Okt. 2020
Kommentiert: Steven Lord am 15 Okt. 2020
Hi everyone!!
I'm trying to write a general solution for a differential equation using a moment method (Galerkin, with polynomials as base functions). When I try to write the general solution por N polynomials, the anonymous function that I'm using, it doesnt update with every loop. I write my code:
N = 10; %number of elements;
l = zeros([N,N]);
g = zeros(N,1);
A = zeros (N,1);
f = @(x) 0;
for i=1:N
for k = 1:N;
l(i,k) = i*k/(i+k+1);
g(k,1) = (k*(8+3*k))/(2*(2+k)*(4+k));
A = linsolve(l,g);
f = @(x) f(x) + A(i,1)*(x - x.^(i+1));
end
end
Thanks!!
  3 Kommentare
Migue Balma
Migue Balma am 15 Okt. 2020
The function I want to create is:
Where the element A(i,1) has the coefficient I want. I use a for in that anonymous function because I want to have it regardless of the value of N. If N = 3, I should have 3 polynomials and so on.
Thank you!!
Steven Lord
Steven Lord am 15 Okt. 2020
Use the sum function and element-wise operations inside the anonymous function.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam am 15 Okt. 2020
if you don't need to use it inside loop. you can define f(x) after for loop:
N = 10; %number of elements;
l = zeros([N,N]);
g = zeros(N,1);
A = zeros (N,1);
for i=1:N
for k = 1:N;
l(i,k) = i*k/(i+k+1);
g(k,1) = (k*(8+3*k))/(2*(2+k)*(4+k));
A = linsolve(l,g);
f = @(x) f(x) + A(i,1)*(x - x.^(i+1));
end
end
f = @(x) sum(A'.*(x-x.^(2:N+1)));
  1 Kommentar
Migue Balma
Migue Balma am 15 Okt. 2020
Bearbeitet: Migue Balma am 15 Okt. 2020
Thank you for your answer!! But when I insert and array of values, for example, x1 = linspace (0,1). It gives me an error, that can't evaluate f(x1) to represent it in a plot, I don't know why.
Edit: I solve it using another ''for'' to evaluate the function:
x1 = linspace(0,1)
f1 = zeros(1,length(x1));
for j = 1: length (x1);
f1(j) = f(x1(j));
end
Thank you so much!! You solved my question!

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

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by