Trying to create a simple function Matlab gives me an error message

3 ビュー (過去 30 日間)
AStar
AStar 2019 年 10 月 2 日
コメント済み: Walter Roberson 2020 年 2 月 3 日
Im trying to create a function called "vecout" which receives an integer number and will output a vector that starts with the vector itself and increments until it reaches the given vector +5
it should work like this
vecout(4)
=4 5 6 7 8 9
This is my code that I have written as a script. when i enter vecout(4) for example in my command window i get an error message that says"function vecout has already been declare within this scope". Matlab doesnt let me use my function.Please help. How can I make this function work?
function B=vecout(a)
B=a:a+5;
end

回答 (3 件)

Zhousheng Chen
Zhousheng Chen 2019 年 11 月 1 日
Is there any "clear" or "clc" before the function in the vecout.m file?

James Tursa
James Tursa 2019 年 10 月 2 日
Put your vecout( ) function code in a separate file called vecout.m
  1 件のコメント
AStar
AStar 2019 年 10 月 2 日
I have already saved my file as vecout.m

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


Saroj Si
Saroj Si 2020 年 2 月 3 日
Same problem I also faced. I think it is only due to presence of clc,clear or clear all before function.
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 2 月 3 日
It is not exactly that, but the presense of any commands before the function statement would make the file into a script file. From R2016b and later, it is legal to define a function inside a script file. However, when you do define a function inside a script file, the name of the function must be different than the name of the script, and if you try to use the same name for the function and the script you will get exactly the noted error about the function already being declared in the scope.
Note that clear all should almost never be put into a function or script file: using "clear all" inside your code is like blowing up the bridge you are standing on while hoping that in the explosion you will just happen to land exactly balanced on one toe.

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by