multi-variable function, sum over one variable
显示 更早的评论
I have a function of three variables N(z,t,n). I'd like to sum over only integers of n such that I am left with N(z,t), where z and t can be arrays of any length.
I've tried:
NN = 1:2000;
sum_function = @(z,t) sum(f(z,t,NN));
where f is a previously defined function of @(z,t,n), but this still requires that z and t have the same size as NN.
How do I evaluate this sum properly?
回答(1 个)
Maybe something like this
z = 1:3;
t = 1:4;
NN = 1:2000;
% Evaluate f(z,t,n) for each element of NN,
% storing all results in cell array C
C = arrayfun(@(n)f(z,t,n),NN,'uni',0);
% Inspect the first and last elements of C
disp(C{1}); disp(C{end});
% Concatenate all elements of C along the 3rd dimension
% and then sum that 3d matrix along the 3rd dimension.
% This will work as long as all elements of C are the
% same size; whether that's true depends on the
% definition of f.
result = sum(cat(3,C{:}),3)
function out = f(z,t,n)
% Some function where z and t are vectors, n is a scalar.
% In this case, out is a matrix of size numel(z)-by-numel(t),
% but out can be any size as long as its size only depends on
% the sizes of z and t.
out = z(:).*t(:).'.*n;
end
4 个评论
Walter Roberson
2022-5-3
I would use a variation on that:
sum_function = @(z,t) sum(arrayfun(@(n)f(z,t,n),NN));
That'll work if f returns a scalar
z = 1:3;
t = 1:4;
NN = 1:2000;
sum_function = @(z,t) sum(arrayfun(@(n)f_scalar(z,t,n),NN));
sum_function(z,t)
But not otherwise
sum_function = @(z,t) sum(arrayfun(@(n)f_non_scalar(z,t,n),NN));
sum_function(z,t)
[Even then, the outputs from f have to be the same size for all n (and if that's not the case then the question doesn't make sense - at least, not to me).]
Of course, without knowing what f is, it's hard to say how general the solution needs to be.
function out = f_scalar(z,t,n)
out = n;
end
function out = f_non_scalar(z,t,n)
out = n*ones(1,10);
end
Nicolas Couture
2022-5-3
Walter Roberson
2022-5-3
The second parameter to sum() can be the dimension to sum over.
类别
在 帮助中心 和 File Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!