I have some simple function that takes in a value
This value is the checked off a number of if or elseif statements to calculate another value.
The problem is it seems to find an error when trying to run which says
Error using / Matrix dimensions must agree.
Error in abc (line 9) a = 5000 / g;
the code is as follows
function abc(g)
if (g == 100)
a = 1;
elseif (g <= 99 & g >= 50)
a = 200 -2*g;
elseif (g <= 50 & g >= 1)
a = 5000 / g;
else
warning('Invalid value passed, a defaults to 1');
a =1;
end
end
So, im passing in abc 100 and i expect a to be 1 but instead it runs through each if / elseif and throws an error on a = 5000/g
I should also mention that i initially tried using && in the elseifs but this also gave an error which said
Operands to the || and && operators must be convertible to logical scalar values.
Error in abc (line 6) elseif (g <= 99 && g >= 50)
Anybody any idea whats going on here ? Thanks
You are probably passing a matrix to your function, e.g. when you call
abc(yourdata)
yourdata
is actually not one number, but a matrix. If you called directly
abc(100)
you should not see your problem (or do you?).
In other words, your main problem is not inside your function, but when you call it!
Given your description, it seems that you set yourdata(1)
to the value 100 that you want to test, but some other element of the matrix has a different value, which is why the if
construct branches into the else case. There, you need ./
instead of /
if you want to do element-wise division instead of matrix division.
But really you probably just need to make sure that yourdata
is scalar when you call your function.