How to Work with seperate function files?
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Nathaniel Denham
am 9 Feb. 2023
Beantwortet: Nathaniel Denham
am 10 Feb. 2023
Hello! I am currently computing the sum of a geometric series of the form ar^n where n is a range of 0,12 and I need to do it in a seperate function file and then reference it, but I keep getting this error when I try to have the function typed into my file, it says cant be found, even though they are in the same folder. Here is my work for both ways of taking the geometric sum which I am doing.


2 Kommentare
dpb
am 9 Feb. 2023
Can't really tell what files you have nor what your code is that you're trying to execute that doesn't work...but the reference to the m-file is the file name (and is case-sensitive), NOT the function name inside the file--they should match identically, of course, but it is the file name that wins if they don't.
Show what the result of
which -all geosum1
which -all geosum2
returns at the command line as well as
cd
dir geosum*.m
NB: on the third exercise note that you can now create functions inside script files, but to do so the functions must be enclosed in the function....end construct for each function; your above function appears to be missing the closing end; this could be part of the issue, but we can't really see enough to know just what you've done that it doesn't like
Akzeptierte Antwort
Weitere Antworten (3)
Sulaymon Eshkabilov
am 10 Feb. 2023
Here is one M-file that calls and executs built-in fcn file in it. Note in the defined fcn file called geosum1 there is an err, i.e., the variables "S" adn "a" are not pre-defined. This is the corrected code:
r = [-5 2 3 6 8];
n = 4;
S = geosum1(r,n)
function S = geosum1(r, n)
S = 0;
a = 2;
for k = 0:n-1
S = S+(a*r.^k);
end
end
dpb
am 10 Feb. 2023
Verschoben: dpb
am 10 Feb. 2023
Don't use images; post the actual text...then somebody could do something with it...
The above line
type 'geosum1.m'
is a logical error -- the command line form of the command (the one not using parentheses around the argument list as above) interprets all the text after the command as text -- by adding the quotes, you've told it to look for a file that includes the quotes as part of the file name. The proper format for the above is
type geosum1.m
or
type('geosum1.m')
In the first (command line form), the argument is a string; in the second it is necessary to quote the string in order for the argument to not try to be interpreted as a variable.
0 Kommentare
Sulaymon Eshkabilov
am 10 Feb. 2023
Your problem statement says do not define a, r, n inside the function file. That means that these variables need to be input variables.
r = [-5 2 3 6 8];
n = 4;
a = 2;
S = geosum1(r,n, a)
function S = geosum1(r, n, a)
S = 0;
for k = 0:n-1
S = S+(a*r.^k);
end
end
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



