The "unique" function returns "Index exceeds matrix dimensions" error

1 回表示 (過去 30 日間)
Snoopy
Snoopy 2017 年 4 月 14 日
回答済み: Snoopy 2017 年 4 月 14 日
I have a .mat file loaded in the Workspace. I execute the command
unique = unique(datafile.data(:,2));
It creates the unique array successfully. When I execute the very same command for a second time, what should happen? The array 'unique' should be created again and the one in the Workspace should be replaced. No, instead, I get the error 'Index exceeds matrix dimensions.' If I assign the statement to a different name like
a = unique(datafile.data(:,2));
I get the same error. So the first time I execute the command, no problem. The second time I execute it, I get the error. What is going on?
  1 件のコメント
Stephen23
Stephen23 2017 年 4 月 14 日
編集済み: Stephen23 2017 年 4 月 14 日
You redefine unique to be a variable:
unique = unique(..)
so of course MATLAB tries to access that variable the next time you use the name unique.

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

採用された回答

the cyclist
the cyclist 2017 年 4 月 14 日
I'm pretty sure that what is happening is that the first time, you have defined the variable called unique, which is a bad idea because it is the same name as the function.
The second time through that code, MATLAB is trying to access the variable, not the function, so you get the error.
The fact that you get the error again when assigning the output to a suggests to me that you still have the variable named unique in the workspace. Clear that variable out and try again.
  1 件のコメント
Walter Roberson
Walter Roberson 2017 年 4 月 14 日
Right. If you have a variable in scope that is the same name as a function, it is always the variable that is being referred to.
Exception: if you have a function that invokes a script that assigns to a variable that has the same name as a function that you call, or if the function invokes a function that does an assignin('caller') to a variable that is the same as a function name that you call, then the JIT (Just In Time) compiler might keep referring to the function instead of to the variable.

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

その他の回答 (1 件)

Snoopy
Snoopy 2017 年 4 月 14 日
Thanks a lot for the quick and detailed responses.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by