-1
L=1; Nx=51; PeriodicFlag=1; T=15; Nt=51;
spacedef='Pade6FirstDeriv'; casedef='LinearAdvection';


if (spacedef == 'Pade6FirstDeriv')
    D1 = sparse(Pade6(Nx,dx,PeriodicFlag)); 
elseif (spacedef == 'Upwind3FirstDeriv')
    D1 = sparse(Upwind3(Nx,dx,PeriodicFlag));
elseif (spacedef == 'Central4FirstDeriv')
    D1 = sparse(Central4(Nx,dx,PeriodicFlag));    
elseif (spacedef == 'Central2FirstDeriv')
    D1 = sparse(Central2(Nx,dx,PeriodicFlag));
else
    error(sprintf('Unknown spacedef = %s',spacedef));
    end

In the above code, the if section is a small segment from a function I've constructed. I'm trying to get the function to know which methods to use based on my input (spacedef). Central2, Central4, Upwind3, and Pade6 are other functions I've written. The weird thing is that when spacedef =/= to 'Pade6FirstDeriv', I would get an error stating Error using ==, Matrix dimensions must agree. I've tried swapping the order of the if loop (by placing Central4, Central2, Pade6, and Upwind3 in the first line of the loop), and it seems like only the top line of the loop will work (the elseifs are not working). I'd greatly appreciate it if anybody can help me out. Thanks!

  • possible duplicate of [matrix dimension must agree](http://stackoverflow.com/questions/20109738/matrix-dimension-must-agree) – Daniel Mar 07 '15 at 23:20
  • possible duplicate of [Error using == Matrix dimensions must agree](http://stackoverflow.com/questions/25968403/error-using-matrix-dimensions-must-agree) – TroyHaskin Mar 08 '15 at 00:47

1 Answers1

1

As has been noted in the comments, this is a common error when people first start comparing strings in MATLAB, and strcmp or strcmpi is generally the solution.

However, one solution the questions links in the comments don't present, and a solution I think looks much nicer, is the switch statement:

switch (spacedef)
    case('Pade6FirstDeriv')
        D1 = sparse(Pade6(Nx,dx,PeriodicFlag)); 

    case('Upwind3FirstDeriv')
        D1 = sparse(Upwind3(Nx,dx,PeriodicFlag));

    case('Central4FirstDeriv')
        D1 = sparse(Central4(Nx,dx,PeriodicFlag));    

    case('Central2FirstDeriv')
        D1 = sparse(Central2(Nx,dx,PeriodicFlag));

    otherwise
        error(sprintf('Unknown spacedef = %s',spacedef));
end

Note: if I expect others to use my code with string comparisons, I usually lower the input such that the comparison is case-insensitive, although I have not done that here.

TroyHaskin
  • 8,361
  • 3
  • 22
  • 22