Question on summing function handles
1 view (last 30 days)
Show older comments
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 Comments
VBBV
on 24 Mar 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
Accepted Answer
VBBV
on 24 Mar 2022
Edited: VBBV
on 24 Mar 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 Comments
VBBV
on 25 Mar 2022
Edited: VBBV
on 25 Mar 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(:,:))
More Answers (1)
David Hill
on 24 Mar 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');
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!