How to use an anonymous function in a ''for''?
    8 ビュー (過去 30 日間)
  
       古いコメントを表示
    
    Migue Balma
 2020 年 10 月 15 日
  
    
    
    
    
    コメント済み: Steven Lord
    
      
 2020 年 10 月 15 日
            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 件のコメント
  Steven Lord
    
      
 2020 年 10 月 15 日
				Use the sum function and element-wise operations inside the anonymous function.
採用された回答
  Asad (Mehrzad) Khoddam
      
 2020 年 10 月 15 日
        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 件のコメント
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




