Creating a function with equation as an input
13 次查看(过去 30 天)
显示 更早的评论
HI, I am trying to create a function,with an equationas an input so that the equation runs within 4 loops while the values of the equation change with each iteration.
I want to use a function as the process nedds to be repeated for different equations multiiple times.
However matlab does not recognise variable p, i understand it hasnt been defined but im not sure how to input the equation so that it can be read and suitibly substituted in the equation.
I appreciate any assistance thank you
for Sigmainternal = 1:1
%sigma11 refers to 11:==> 1_: First U equation _1: fisrt term in equation.
sigma11 = stepPQ(N, ((p*p1/(p+p1-1))*((1-(-1)^(q+q1+1))/(q+q1+1))) );
end
function [sigma] = stepPQ(N,eqn)
sigma =zeros((N+1)^2,(N+1)^2);
for p=0 : N
for q = 0:N
for p1 = 0:N
for q1 = 0:N
temp = (eqn);
if isnan(temp) %check if divide by 0
temp = 0;
end
row = p*(N+1)+(q+1);
col = p1*(N+1)+(q1+1);
sigma(row,col) = temp ;
end
end
end
end
sigma = sigma + transpose(sigma);
end
0 个评论
采纳的回答
Alan Stevens
2021-4-7
Like this:
%sigma11 refers to 11:==> 1_: First U equation _1: fisrt term in equation.
N = 3; % arbitrary value
sigma11 = @(p,q,p1,q1) p*p1/(p+p1-1)*(1-(-1).^(q+q1+1))/(q+q1+1); % create as a function
sigma = stepPQ(N, sigma11); % call stepPQ with N and the function sigma11
disp(sigma)
function [sigma] = stepPQ(N,eqn)
sigma =zeros((N+1)^2,(N+1)^2);
for p=0 : N
for q = 0:N
for p1 = 0:N
for q1 = 0:N
temp = eqn(p,q,p1,q1); % You have to call the equation with arguments
if isnan(temp) %check if divide by 0
temp = 0;
end
row = p*(N+1)+(q+1);
col = p1*(N+1)+(q1+1);
sigma(row,col) = temp ;
end
end
end
end
sigma = sigma + transpose(sigma);
end
Note that sigma11 isnt an equation, it's a function.
更多回答(1 个)
Julius Muschaweck
2021-4-7
编辑:Julius Muschaweck
2021-4-7
Your "equation" seems to be a function depending on p, p1, q, q1.
I would use an anonymous function to model this behavior. An anonymous function is an object you can feed into another function and evaluate within that other function.
(You also need to define N to make this example run. With N = 3, sigma11 becomes a 4x4 matrix)
for Sigmainternal = 1:1
%sigma11 refers to 11:==> 1_: First U equation _1: fisrt term in equation.
% define N
N = 3;
% define equation
eqn = @(p, p1, q, q1) ((p*p1/(p+p1-1))*((1-(-1)^(q+q1+1))/(q+q1+1)));
sigma11 = stepPQ(N, eqn );
end
function [sigma] = stepPQ(N,eqn)
sigma =zeros((N+1)^2,(N+1)^2);
for p=0 : N
for q = 0:N
for p1 = 0:N
for q1 = 0:N
temp = eqn(p,p1,q,q1);
if isnan(temp) %check if divide by 0
temp = 0;
end
row = p*(N+1)+(q+1);
col = p1*(N+1)+(q1+1);
sigma(row,col) = temp ;
end
end
end
end
sigma = sigma + transpose(sigma);
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Particle & Nuclear Physics 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!