Function to Vector

32 ビュー (過去 30 日間)
Dustin
Dustin 2012 年 1 月 19 日
Hello all,
I am currently attempting to have my function be able to output a vector into the workspace. Currently i have tried to something like this (simplified a lot but this is the jist of it)
for i = 1:10
a(i) = crr(x)
end
where a(i) is supposed to be my output vector and crr is my function, x is some vector that crr acts on. crr just outputs one numerical value. even when i do something like a = crr(x) i get an error message that says "too many output values"
if anybody knowss a way that allows crr to output a vector into the workspace, your help would be much appreciated.
dustin
  2 件のコメント
the cyclist
the cyclist 2012 年 1 月 19 日
Can you post a (possibly simplified) version of the function crr() that give the error message?
Also, you could use the debugger ("dbstop if error") to halt execution when the error occurs, to see exactly what your variables look like.
Dustin
Dustin 2012 年 1 月 19 日
function crr(cc)
vals;
cc=cc/sum(cc);
afc = sum(com(310:359,:))./sum(com(:,:));
afr = sum(ray(310:359,:))./sum(ray(:,:));
TcrossI = 0;
TcrossO = 0;
for iz = 1:40,
TcrossI = TcrossI + (sum(sigma143(iz,2:4)))*cc(iz);
TcrossO = TcrossO + (sum(sigma137(iz,2:4)))*cc(iz);
end
TcrossC = TcrossO + TcrossI;
TcrossR = TcrossI + TcrossI;
Ct = 0;
Rt = 0;
for iz = 1:40,
Ct = Ct + afc(iz)*sigma143(iz,3)*cc(iz);
Rt = Rt + afr(iz)*sigma143(iz,2)*cc(iz);
end
Tcom = Ct/TcrossC;
Tray = Rt/TcrossR;
CRratio = Tcom/Tray;
disp(CRratio)
This is the code, its nothing too complicated, im mostly interested in the value CRratio as output in the work space. cc is a vector, and im interested in changing several elements of cc in order to generate multiple CRratios as a vector. I hope that made sense!

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

回答 (3 件)

Andrew Newell
Andrew Newell 2012 年 1 月 19 日
It is very natural for functions to output vectors in MATLAB. See the documentation for function for some examples. Here is a very simple example:
function y = crr(x)
y = x.^2;
Store this in a file crr.m, and run:
x = 1:10;
a = crr(x)

Walter Roberson
Walter Roberson 2012 年 1 月 19 日
That error would occur if your function crr() was not defined as returning any values. Andrew's Answer shows what the declaration should look like.

Honglei Chen
Honglei Chen 2012 年 1 月 19 日
If I understand your question correctly, you need to do
for i = 1:10
a(i) = crr(x(i))
end
But you could try arrayfun, e.g.,
a = arrayfun(@crr,x)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by