MATLAB: How to write a function that returns the element that is the center of a vector or matrix

arraycenterfindfunctionsifmatrixvector

how do I start writing a function to do this? I have an idea how to write a script, but not as a function.
example:
123
458
112
ans=[2;5;1]
or
1233
ans=[2,3]

Best Answer

Hi Kimberly,
Your function signature could look something like this:
function [ctr] = find_centre (x)
<code to be filled in by you!>
end
where x is your input (from your examples 1233 or [123;458;112]) and ctr is the found centre of the x (again from your examples, [2 3] or [2;5;1]).
I'm guessing that if your input is a matrix then the output should be the centre of each row?
Since you say that your input can be a vector or a matrix (a string of characters can be a vector so whether your input is a row of characters, numbers, cells, or whatever, the logic should be the same) then you probably want to handle the inputs separately by checking to see if x is a vector or is a matrix using the isvector and ismatrix functions respectively. (Note that a vector can be a matrix but not the other way around, so you will want to start with the vector check.)
If the input is a vector, then check its size/length using either of numel (number of elements) or length. The centre of your vector then will be dependent upon whether the size is even or odd (as you have shown in your examples) and you can then extract it from x and set it in ctr via the ctr = x(cstart:cstop); where cstart and cstop are the centre start and stop indices within the vector. From your example of 1223, then cstart=2 and cstop=3. If just 123, then cstart=2 and cstop=2 as well.
If the input is a matrix then you can get the number of rows and columns and do something similar to the above.
Geoff