Matrix dimensions must agree

Hello!
I have written the code which uses a function
function f1=F_1(y,z);
global gamma
global a
f1=-(1/2)*exp(-(z-a)./(1+gamma*cos(2*pi*y)))+1/2;
end
When I try to run I get a error Error using / Matrix dimensions must agree
Could you please help me?
Thank you in advance.
Elena

 Réponse acceptée

the cyclist
the cyclist le 28 Jan 2012

0 votes

Guessing you need .* rather than just * after gamma.
If that does not fix it, can you please specify what the sizes of your variables a,gamma,y,z are?

2 commentaires

Elena
Elena le 28 Jan 2012
Thank you very much. and sorry I'm very new in Matlab
Image Analyst
Image Analyst le 28 Jan 2012
If that was the correct answer, then gamma MUST have been an array. If so, then your code is not very robust. For example, you don't have a try/catch. What guarantees that gamma has the same number of elements as y? Are you checking for that before you call this function? A robust function would check for that inside itself rather than assume. Even if it did assume, it should have a try/catch just in case, so that you can inform your user of some error. Better would be if you passed in gamma and a rather than make them global, but I know that if gamma and a were not available in the calling routine that it might be more convenient to make them global rather than passing them down through a bunch of nested functions that don't use them. Try using code such as this
function f1=F_1(y,z) % Note: I did not use a semi colon like you did.
global gamma
global a
f1 = []; % Initialize - needed in case of error.
try
lz = length(z);
lg = length(gamma);
ly = length(y);
if lz ~= ly || lg ~= ly
errorMessage = sprintf('Dimensions do not match.\nz had %d elements.\ngamma has %n elements.\ny has %d elements', lz, lg, ly);
uiwait(warndlg(errorMessage));
return;
end
% If we get to here, the dimensions match.
f1=-(1/2)*exp(-(z-a)./(1+gamma.*cos(2*pi*y)))+1/2;
catch ME
% Some other kind of error.
errorMessage = sprintf('Error in function F_1.\n\nError Message:\n%s', ME.message);
fprintf(1,'%s\n', errorMessage);
uiwait(warndlg(errorMessage));
end

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 28 Jan 2012

0 votes

You should really learn how to use the debugger. It's much more efficient than asking us for every simple thing like this. For example, if you put a breakpoint at that line and examine the lengths of y,z, gamma, and a, you'll probably find that some of them aren't scalars and those that aren't don't have the same lengths.

Catégories

En savoir plus sur Debugging and Improving Code dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by