About function in methods of a class

조회 수: 2 (최근 30일)
Tony Kaywood
Tony Kaywood 2020년 9월 28일
답변: Steven Lord 2020년 9월 28일
Hi guys, I'm doing a project.
To use function in methods of one of my class I defined, I made this one :
function [y, Fs] = getRandomMusic(feeling)
path_name = strcat('C:\Users\Jack\Desktop\music','\',feeling);
music_lists = dir(path_name);
music_number = length(music_lists);
ran_music_number = randi(music_number);
while ran_music_number < 3
ran_music_number = randi(music_number);
end
file_name = strcat(path_name,'\',music_lists(ran_music_number).name);
[y, Fs] = Audioread(file_name, native);
end
This is the function when input "feeling", then it returns [y, Fs] of randomly selected from the "feeling" folder.
But when I rud the main MATALB file to use this function, it makes an error messgae like this :
Check the function 'getRandomMusic' for missing arguments or invalid argument data types. (It's not official message cuz my mother tongue isn't english)
Can anyone suggest something to me?
Thanks!
  댓글 수: 3
Tony Kaywood
Tony Kaywood 2020년 9월 28일
Thanks for the comment. I meant to say I had defined function in class file and there had some proplem when I called the function in another MATLAB file.
per isakson
per isakson 2020년 9월 28일
"defined function in class file" There is a problem with nomenclature. In Matlab methods of classes are defined with the keyword, function.
classdef MyClass
methods
function [y,Fs] = getRandomMusic( obj, feeling )
end
end
end
In this basic case you have to take the instance variable, obj, as the first input argument.

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2020년 9월 28일
If getRandomMusic is a non-Static method of a class (which I'll call iPod just to have some way to refer to the class) then at least one of the inputs to getRandomMusic must be an iPod object. If you try to call it without at least one iPod object, MATLAB won't know to what getRandomMusic refers.
You could make feeling an iPod object, or you could have getRandomMusic accept two inputs (one an iPod object and one a char vector or string, based on the context.)
p = iPod;
[y, Fs] = getRandomMusic(p, 'happy');
Other options include making getRandomMusic a Static method of the iPod class, in which case you would need to call it using the class name:
[y, Fs] = iPod.getRandomMusic('happy');
or turning getRandomMusic into a function rather than a method. If it's only intended to be called from within methods of the iPod class it could be a class-related function defined in the classdef file but after the end keyword associated with the classdef keyword. If you intend it to be called from outside the class as well I'd define it as a regular function in its own file.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by