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.
example:
123
458
112
ans=[2;5;1]
or
1233
ans=[2,3]
  댓글 수: 4
Kimberly
Kimberly 2014년 4월 17일
oh I see. The first should be a matrix, [1,2,3;4,5,8;1,1,2] The second [1,2,2,3]

댓글을 달려면 로그인하십시오.

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Sven
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
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.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by