Question on summing function handles
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi all, I'm relatively new to MATLAB, and have been writing an algorithm for some time now. I've run into a problem where a function S(t,x) is the summation of another function. Below is the code and I'll explain more after:
t = linspace(0,2*pi,9);
x = linspace(-0.5,0.5,5);
Coords = combvec(t,x)'; % Creates the combination of all t with all x
% Finding the set N1
for i = 1:length(Coords)
if (Coords(i,2)>0)
N1(i,j) = Coords(i,j)
end
end
N1 = N1(any(N1,2),:);
This creates a vector of coordinates (t,x) which we want to use. I essentally want to find the below function using all coordinates (tj,xj) from this set N1.
I've tried writing the following but it's clearly wrong and not sure what to do: (note that fj is another function that depends only on these points inside the set N1.
for j = 1:length(N1)
tj = N1(j,1)
xj = N1(j,2)
fj = sin(tj)-sign(xj)
S1 = @(t,x) sum((-56*(1-sqrt((x-xj)^2+(t-tj)^2))^6*(35*sqrt((x-xj)^2+(t-tj)^2)^2+18*sqrt((x-xj)^2+(t-tj)^2)+3)*((xj-x)*fj+(tj-t))))
end
Any help would be highly appreciated.
2 Kommentare
VBBV
am 24 Mär. 2022
Note that your t and x vectors are not of same length. You need to make them equal in order to add.
t = linspace(0,2*pi,9);
x = linspace(-0.5,0.5,9);% here
Akzeptierte Antwort
VBBV
am 24 Mär. 2022
Bearbeitet: VBBV
am 24 Mär. 2022
for j = 1:length(N1)
% remaining code here
S1 = @(t,x) ((-56.*(1-sqrt((x-xj).^2+(t-tj).^2)).^6.*(35*sqrt((x-xj).^2+(t-tj).^2).^2+18*sqrt((x-xj).^2+(t-tj).^2)+3).*((xj-x).*fj+(tj-t))))
S11(j,:) = S1(t,x);% assuming t and x are defined as earlier
end
S11 = sum(S11(:,:))
You can sum S1 outside of loop after computing it.
2 Kommentare
VBBV
am 25 Mär. 2022
Bearbeitet: VBBV
am 25 Mär. 2022
t = linspace(0,2*pi,9);
x = linspace(-0.5,0.5,9); % this is important change
Coords = combvec(t,x)' % Creates the combination of all t with all x
% Finding the set N1
for j = 1:length(Coords)
if (Coords(j,2)>0)
N1(j,:) = Coords(j,:);
end
end
N1 = N1(any(N1,2),:);
for j = 1:length(N1)
tj = N1(j,1);
xj = N1(j,2);
fj = sin(tj)-sign(xj);
S1 = @(t,x) ((-56.*(1-sqrt((x-xj).^2+(t-tj).^2)).^6.*(35*sqrt((x-xj).^2+(t-tj).^2).^2+18*sqrt((x-xj).^2+(t-tj).^2)+3).*((xj-x).*fj+(tj-t))));
S11(j,:) = S1(t,x);% assuming t and x are defined as earlier
end
S11 = sum(S11(:,:))
Weitere Antworten (1)
David Hill
am 24 Mär. 2022
No need for for-loop
t = linspace(0,2*pi,9);
x = linspace(-0.5,0.5,5);
[T,X]=meshgrid(t,x);
fj = sin(T)-sign(X);
S = @(t,x) sum((-56*(1-sqrt((x-X).^2+(t-T).^2)).^6.*(35*sqrt((x-X).^2+(t-T).^2).^2+18*sqrt((x-X).^2+(t-T).^2)+3).*((X-x).*fj+(T-t))),'all');
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!