Output Argument Error - How to Define The Output Argument for a Function

I'm trying to create and use the following function:
function [dctmatrix]=dctmatrix(i,j,N)
if i==1
dctmatrix=sqrt(1/N);
elseif i>=2
dctmatrix=sqrt(2/N)*cos((pi*(2*j-1)*(i-1))/(2*N));
end
end
But whenever I try to use it as follows, I get this error:
i=1:512;
j=1:512;
Y=dctmatrix(i,j,512);
Yinv=transpose(dctmatrix(i,j,512));
X_gray1comp=Y*X_gray1*Yinv;
Output argument "dctmatrix" (and maybe others) not assigned during call to "dctmatrix".
Error in Project2code (line 100)
Y=dctmatrix(i,j,512);
I thought that since I said "dctmatrix=..." in the code for the function itself, that that counted as an output argument. I don't understand how what I've done is wrong. :/

回答 (1 件)

James Tursa
James Tursa 2016 年 10 月 26 日
編集済み: James Tursa 2016 年 10 月 26 日

0 投票

Don't have the return variable name the same as the function name. Use a different name for the return variable (e.g., "result"). Also, you need to use vectorized calculations if you want your function to operate on non-scalar inputs for i and j. So you will need to adjust your i==1 and i>=2 tests to account for vector inputs, and you will need to adjust your cos(etc) calculation for vector inputs.

3 件のコメント

Mel Smith
Mel Smith 2016 年 10 月 27 日
I made the following adjustments and got the same error:
function dct=dctmatrix(i,j,N)
if i==[1]
dct=sqrt(1/N);
elseif i>=[2]
dct=sqrt(2/N)*cos((pi*(2.*j-1).*(i-1))/(2*N));
end
end
i=[1:512];
j=[1:512];
Y=dctmatrix(i,j,512);
Yinv=transpose(dctmatrix(i,j,512));
X_gray1comp=Y*X_gray1*Yinv;
Steven Lord
Steven Lord 2016 年 10 月 27 日
The body of the if section will be executed only if ALL of the elements of i == 1 are true. You're calling this function with i = 1:512. Are ALL the elements of 1:512 equal to 1?
Similarly, the body of the elseif section will be executed only if ALL the elements of i >= 2 are true. Are ALL the elements of 1:512 greater than or equal to 2?
You're probably going to want to use logical indexing in this situation.
Walter Roberson
Walter Roberson 2016 年 10 月 27 日
Suppose an input was less than 1, or was in the range (1, 2) exclusive such as sqrt(2), then you would not generate an output.

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

カテゴリ

質問済み:

2016 年 10 月 26 日

コメント済み:

2016 年 10 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by