I have a function that i want to return the first and last word from a string. so for example firstAndLast('matlab') should give me (m,b), however i am only able to get the first letter from this function?
function [first,last] = firstAndLast(instring)
first=instring(1);
last=instring(length(instring));
end

댓글 수: 6

Stephen23
Stephen23 2016년 5월 5일
편집: Stephen23 2016년 5월 5일
Your question is not clear: you write that you "want to return the first and last word from a string", but then your example seems to return the first and last letters: "firstAndLast('matlab') should give me (m,b)"
Which do you really want: the letters (like your example), or the words (like your explanation) ?
Ian Tee
Ian Tee 2016년 5월 5일
opps sorry, to clarify i would enter the word and input it as a string in the function. Therefore i would like to extract the first and last input of the string.
Stephen23
Stephen23 2016년 5월 5일
What does "extract the first and last input of the string" mean ?
Do you want the first and last letters, or words ?
Ian Tee
Ian Tee 2016년 5월 5일
letters
Stephen23
Stephen23 2016년 5월 5일
편집: Stephen23 2016년 5월 5일
This is what your code does: I suspect that the problem is that were calling your function with only one output, instead of the two that it requires. In any case, in my answer I gave you a simpler way of doing this.
Ian Tee
Ian Tee 2016년 5월 5일
Thank you very much :) , turns out calling it was the problem.

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

 채택된 답변

Stephen23
Stephen23 2016년 5월 5일
편집: Stephen23 2016년 5월 5일

2 개 추천

Words
>> C = regexp('the quick brown fox','\S+','match');
>> C([1,end])
ans =
'the' 'fox'
Letters
>> fun = @(s)s([1,end]);
>> fun('matlab')
ans =
mb

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2016년 5월 5일

댓글:

2016년 5월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by