Function to Vector

29 Ansichten (letzte 30 Tage)
Dustin
Dustin am 19 Jan. 2012
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 Kommentare
the cyclist
the cyclist am 19 Jan. 2012
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 am 19 Jan. 2012
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!

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Andrew Newell
Andrew Newell am 19 Jan. 2012
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 am 19 Jan. 2012
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 am 19 Jan. 2012
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)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by