How to write a function that returns the element that is the center of a vector or matrix?
조회 수: 24(최근 30일)
표시 이전 댓글
how do I start writing a function to do this? I have an idea how to write a script, but not as a function.
댓글 수: 4
Geoff Hayes 2014년 4월 17일
Your function signature could look something like this:
function [ctr] = find_centre (x)
<code to be filled in by you!>
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.
댓글 수: 12
Sven 2014년 4월 17일
편집: Sven 2014년 4월 17일
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
Sven 2014년 4월 21일
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.
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!