Indexing Results of a For Loop When the Input Comes from a Function

조회 수: 1 (최근 30일)
Jeremy
Jeremy 2018년 3월 10일
답변: Jeremy 2018년 3월 11일
I just started using functions as loop inputs and never had to index the results before. My goal is to store the results of rpf_cba and vpf_cba into a matrix. Here's what I'm working with:
for i=0:h:11940
[r_step_cba, v_step_cba] = RK4_single_step(mu, rpf_cba, vpf_cba, h);
i = i+h;
rpf_cba = r_step_cba;
vpf_cba = v_step_cba;
semi_cba = -(norm(rpf_cba)*mu)/((norm(rpf_cba)*norm(vpf_cba)^2)-(2*mu)).*semi_store
i = i+1;
end
I'm quite used to indexing loop results and tried all of the usual methods (preallocation, index variable, etc.) but after spending a couple of days on this, I cannot figure out what's going on. The most common error I get is this:
In an assignment A(I) = B, the number of elements in B and I must be the same. Error in Exam_2_Question_4 (line 60) rpf_cba(i) = r_step_cba;
which makes me think the loop and function aren't looking in the same place for results to actually index. Alternatively, if I take the semi_ones variable and multiply it by r_step_cba, I get a 'Matrix dimensions must agree' error. If anyone has some experience with this, I'd be grateful for some advice. Also, let me know if more code is needed; the input function is pretty big so I didn't want to clutter things from the start. Thank you very much!

채택된 답변

Abraham Boayue
Abraham Boayue 2018년 3월 11일
[r_step_cba, v_step_cba] = RK4_single_step(mu, rpf_cba, vpf_cba, h)
for i = 0:h:11940
i = i+h;
rpf_cba = r_step_cba;
vpf_cba = v_step_cba;
semi_cba = (norm(rpf_cba)*mu)/((norm(rpf_cba)*norm(vpf_cba)^2)-(2*mu))*semi_ones;
i = i+1;
end
  댓글 수: 2
Abraham Boayue
Abraham Boayue 2018년 3월 11일
Try to separate your comments from your code. It makes it difficult to understand the problem that you are having.
Jeremy
Jeremy 2018년 3월 11일
Thanks for the heads up. I realized the "Code" button would do the trick.

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

추가 답변 (1개)

Jeremy
Jeremy 2018년 3월 11일
Nevermind. Just figured it out. In case this helps anyone, here's what I did...pretty simple, now that I think about it:
semi_store = [];
rpf_store = [];
vpf_store = [];
semi_ones = ones(1,200);
i = 0;
for t=0:step:11940
[ r_step, v_step ] = RK4_single_step_cba_plus_drag(mu, rpf, vpf,...
step);
t = t+step;
rpf = r_step;
vpf = v_step;
semi_drag = -(norm(rpf)*mu)/((norm(rpf)*norm(vpf)^2)-(2*mu));
rpf_store = [rpf_store rpf]
vpf_store = [vpf_store vpf];
semi_store = [semi_store semi_drag];
i = i+1;
end
I realized it is possible to pass an empty matrix into a for loop and use the results from the function to populate it. Now I'm sure for the savvy programmer, this was a "well, no duh" solution. For the rest of us, though, there you go.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by