Creating a function with equation as an input
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (1)
Julius Muschaweck
am 7 Apr. 2021
Bearbeitet: Julius Muschaweck
am 7 Apr. 2021
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
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!