# Help with scope issue in Matlab

4 views (last 30 days)
Brendan Zotto on 17 Sep 2016
Answered: hello_world on 6 Jul 2018
Hey I am trying to figure out how to get the follow code to compile in Matlab, I am new to the language, (mainly from C background), and I think I am getting a scope issue in my first for loops. I am getting an undefined variable error. Specifically "Undefined function or variable 'M'. I use M in the nested for loops, and want to multiply it by M2, i dont know how to do this,Can someone help me fix this, and get this function working? Any help is appreciated.
function r = mfcc(s,fs)
m = 100;
n = 256;
l = length(s);
nbFrame = floor((1-n)/m) + 1;
for i =1:n
for j = 1:nbFrame
M(i,j) = s(((j-1)*m)+i);
end
end
h = hamming(n);
M2 = diag(h) * M;
for i = 1:nbFrame
frame(:,i) =fft(M2(:,i));
end
t = n/2;
tmax = 1/ fs;
m = melfb(20,n, fs);
n2 = 1 + floor(n/2);
z = m * abs(frame(1:n2,:)).^2;
r = dct(log(z));

Star Strider on 17 Sep 2016
Edited: Star Strider on 17 Sep 2016
MATLAB is case-sensitive, so m ~= M.
You have several problems, however. You use both ‘m’ and ‘M’ in different contexts in your code.
I would initially reassign ‘M’ as:
M = 100;
but then you need to decide what you want to do with:
M(i,j) = s(((j-1)*m)+i);
because this now creates a matrix ‘M’, using ‘m’ to calculate it.
You later assign:
m = melfb(20,n, fs);
and use it to calculate:
z = m * abs(frame(1:n2,:)).^2;
further confusing the issue. You can see how MATLAB would get confused, much as I would be confused if I didn’t switch contexts, and I’m quite definitely not certain what you’re referring to. Eliminate the ambiguities and all will be well. I would use different variable names and assignments as necessary to avoid confusion and make your code easier to follow. MATLAB does not restrict you to specific variable name lengths (providing you don’t overdo it), so ‘M_constant’, ‘M_matrix’ and ‘final_result’ are all both valid and descriptive. The typing can get tedious, but that’s the worst that can be said about it.
I would also comment-document it, because that will help you understand what you’re doing, will tell other people what you’re doing, and you will need those descriptions when you come back to your code in a while and have to figure out what you were thinking. (Believe me, you won’t remember the details in a few days and especially in a few weeks.)
LATER THAT SAME MINUTE I see some other problems and inefficiencies, but lets get the ‘M,m’ problem sorted first.
Star Strider on 18 Sep 2016
understand. However please understand that in order for me to understand what your code is doing, need to know what you intend it to do, and what the parameters (constants) are. By running it, can understand what it’s doing, so only if it°s not possible for me to put that in the context of what it should be doing will need help to understand it.

hello_world on 6 Jul 2018
Hello,
Any progress on this code so far?
If so, can you share the code?