Undefined function or variable 'a'.

My current problem refers to the below script and function.
clear;
for x=100:145
assfunct1(x);
fprintf('x: %d, a: %d, b: %d, c: %d\n', x, a, b, c);
end;
&
function [a,b,c] = assfunct1(x)
if x<0 || fix(x) ~=x;
disp('error, input is not a non negative integer')
return
end
for a=1:x
b=sqrt(5*a^3);
c=sqrt((a+b)^2);
end
[a,b,c]
end
>> Assignment1
ans =
1.0e+03 *
0.1000 2.2361 2.3361
Undefined function or variable 'a'.
Error in Assignment1 (line 4)
fprintf('x: %d, a: %d, b: %d, c: %d\n', x, a, b, c);
Been trying for hours to work where I have erred, ty for any help you can offer.

3 件のコメント

Image Analyst
Image Analyst 2016 年 5 月 3 日
You forgot to give the code for assfunct3(). You only gave it for assfunct1().
And can we assume that the code starting with "clear" is in a separate m-file, and not below assfunct1() definition in the same file?
Scott
Scott 2016 年 5 月 4 日
yes that's a typo, the code is for assfunct1 in the script
CS Researcher
CS Researcher 2016 年 5 月 4 日
I answered this a few days back and as John correctly pointed out you should do this:
clear;
for x=100:145
[a,b,c] = assfunct1(x);
fprintf('x: %d, a: %d, b: %d, c: %d\n', x, a, b, c);
end;

サインインしてコメントする。

 採用された回答

John BG
John BG 2016 年 5 月 3 日

0 投票

You have to collect the output of your custom function assfunct3() with a variable that then you have to feed in the fprintf.
Since you call assfunct3 but do not collect the result with anything, then fprintf does not really know what variable 'a' is because the 'a' you use in the header of the assfunct3 remains local to that function.
If you find this answer of any help solving your question,
please click on the thumbs-up vote link,
thanks in advance
John

その他の回答 (1 件)

Jan
Jan 2016 年 5 月 3 日

1 投票

You have to catch the outputs of the function:
for x = 100:145
[a, b, c] = assfunct3(x);
fprintf('x: %d, a: %d, b: %d, c: %d\n', x, a, b, c);
end
Note that the values of b and c are overwritten in each iteration:
for a = 1:x
b = sqrt(5*a^3);
c = sqrt((a+b)^2);
end
[a,b,c]
What is your intention?

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

タグ

質問済み:

2016 年 5 月 3 日

コメント済み:

2016 年 5 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by