MATLAB Answers

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

176 views (last 30 days)
Kimberly
Kimberly on 17 Apr 2014
Commented: Sven on 21 Apr 2014
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]
  4 Comments

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 17 Apr 2014
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
  12 Comments
Kimberly
Kimberly on 21 Apr 2014
Thank you for all your help. I played around with it and got it to run for both matrices and vectors.

Sign in to comment.

More Answers (1)

Sven
Sven on 17 Apr 2014
Edited: Sven on 17 Apr 2014
Hi Kimberly, try this:
% Set up some input
x = [1 2 3
4 5 8
1 1 2]
% Grab the middle column(s)
xMidVal = (size(x,2)+1) / 2;
midInds = unique([floor(xMidVal) ceil(xMidVal)]);
out = x(:,midInds)
Did that answer the question for you?
  4 Comments
Sven
Sven on 21 Apr 2014
Ha, thanks SS :)
Kimberley, you are receiving quite detailed answers from Geoff who has (kindly) devoted time to helping you. I think that an hour or so reading some of the getting started guide will also be of much benefit. Two topics: Matrices and arrays and Programming and scripts would be great places to start.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by