필터 지우기
필터 지우기

How do I create an array of a function output?

조회 수: 79 (최근 30일)
FortuitousMonkey
FortuitousMonkey 2018년 2월 25일
댓글: Cedrick De Block 2020년 11월 10일
How do I create an array of a function output? Each attempt I've tried it overwrites the value in the array and returns a 1x1 array with the final value calculated as it's value.
I've seen nested list functions or push functions? Which is the best for the below case and how do I implement it?
Apologies if this is a simplistic question, just struggling with this problem.
My function is:
>> m=0:1:3
>> n=0:1:4
>> for a=m
for b=n
res=ack(a,b)
end
end
function res=ack(m,n)
if m==0
res = n+1;
elseif m>0 && n==0
res = ack(m-1,1);
elseif m>0 && n>0
res = ack(m-1,ack(m,n-1));
end
end
  댓글 수: 1
David Fletcher
David Fletcher 2018년 2월 25일
편집: Stephen23 2018년 2월 26일
Essentially your problem is very similar to the answer I provided for
Maybe not the 'best' way to do it, but it is pretty much the answer to the problem you are outlining

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

채택된 답변

Stephen23
Stephen23 2018년 2월 26일
Method one: nested loops and indexing
m = 0:3;
n = 0:4;
out = nan(numel(m),numel(n));
for km=1:numel(m)
for kn=1:numel(n)
out(km,kn) = ack(m(km),n(kn));
end
end
giving:
out =
1 2 3 4 5
2 3 4 5 6
3 5 7 9 11
5 13 29 61 125
Method two: arrayfun:
>> [M,N] = ndgrid(m,n);
>> out = arrayfun(@ack,M,N)
out =
1 2 3 4 5
2 3 4 5 6
3 5 7 9 11
5 13 29 61 125
  댓글 수: 2
FortuitousMonkey
FortuitousMonkey 2018년 2월 26일
Both work for me.
Thanks for helping.
Cedrick De Block
Cedrick De Block 2020년 11월 10일
hello excuse me,
in your fist example I have a problem with "ack"
matlab doesn't reconise it, is it a function?

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 2월 25일
  댓글 수: 1
FortuitousMonkey
FortuitousMonkey 2018년 2월 26일
Could you help me implement this in my code, please? I am drawing a blank (relatively new to matlab).

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by