Summation of Function Handle Cells

조회 수: 10 (최근 30일)
AeroLad
AeroLad 2020년 3월 30일
댓글: Omid Feizi 2021년 5월 23일
Hello.
I am trying to sum up each individual cell that is produced by a function handle in a for loop that runs from.
My handle looks like this:
for a = 1 : 11;
f{a} = @(u)1
for b = setdiff(1:11, a);
f{a} = @(u)1.*G.*mass_a.*mass_b.*r./(norm_r^3)
%need to sum up all 11 cells produced here
end
end
The function handle spits out something like this (I have only put 2 cells, there are 11):
{@(u)1.*G.*mass_a.*mass_b.*r./(norm_r^3)} {@(u)1.*G.*mass_a.*mass_b.*r./(norm_r^3)}
I need to sum all of the cells from above up.
It seems like the sum function on matlab does not work. I have seen a couple of instances of loops being used, but can't seem to be able to apply them correctly.
Thanks
  댓글 수: 11
James Tursa
James Tursa 2020년 3월 30일
편집: James Tursa 2020년 3월 30일
@AeroLad: My point is that the way you are currently building your function handles the radius values r_a and r_b are only snapshots of the current r_a and r_b for that iteration. I.e., all of the function handles you are building and summing are only good for one iteration of your calculations. E.g., If you are using this in an iterative integration scheme, you would be forced to completely rebuild all of your function handles from scratch at each step in the iteration process. Is that what you intend? It seems to me that building these function handles doesn't buy you anything. Just calculating the forces directly and summing them would be quicker. But I don't know the overall goal you have.
AeroLad
AeroLad 2020년 3월 30일
Ah. I think I see what you mean. I will look into calculating them directly. It will also most certainly make things faster. Thanks

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 3월 30일
fsum = @(x) sum(cellfun(@(F) F(x), f));
  댓글 수: 2
AeroLad
AeroLad 2020년 3월 30일
Many thanks! All the best and stay safe!
Omid Feizi
Omid Feizi 2021년 5월 23일
It was my question too, your code help me a lot.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by