Entering a whole word into an arary.
조회 수: 7 (최근 30일)
이전 댓글 표시
Hello I just have a simple question. I'm working on a project that calculates the resistor value when the user enters a five color code. I cannot figure out how to put each word as a single element in an array. so if I enter the code as a single string: blue black green red orange, I would like to make a(1)=blue, a(2)=black, etc..
Thanks in advance!
댓글 수: 0
채택된 답변
Matt Fig
2012년 11월 8일
편집: Matt Fig
2012년 11월 9일
This works whether your user enters only commas between words, only spaces, or both (even colons or semicolons!). I test it out in a FOR loop only to see if entering different ways people might use will still get us our values.
for ii = 1:4
% You only need these three lines, no loop.
I = input('Enter the colors you want: ','s');
I(isstrprop(I,'punct')) = ' ';
C = regexp(I(~isstrprop(I,'punct')),'\s+','split')
end
Enter the colors you want: black gold green
C =
'black' 'gold' 'green'
Enter the colors you want: yellow, peach, orange
C =
'yellow' 'peach' 'orange'
Enter the colors you want: purple:spicy:fresh
C =
'purple' 'spicy' 'fresh'
Enter the colors you want: Yummy; grape;cherry
C =
'Yummy' 'grape' 'cherry'
댓글 수: 6
추가 답변 (4개)
Azzi Abdelmalek
2012년 11월 5일
편집: Azzi Abdelmalek
2012년 11월 5일
a={'blue' , 'red', 'green'}
a(1)
a(2)
%or
a=struct('color',{'red','blue','green'})
a(1).color
a(2).color
댓글 수: 10
Walter Roberson
2012년 11월 9일
You can create a figure() that you have the uicontrol() in. listdlg() creates a figure and appropriate controls for its operations; the only difference is that it is already written for you.
Walter Roberson
2012년 11월 5일
편집: Walter Roberson
2012년 11월 5일
Not possible. See http://www.mathworks.co.uk/matlabcentral/answers/52631-create-an-array-contain-no-of-string-adding-one-by-one#answer_64157 for work-around
댓글 수: 0
Image Analyst
2012년 11월 5일
>> theWords = allwords('blue black green red orange')
theWords =
'blue' 'black' 'green' 'red' 'orange'
theWords is a cell array because the words can have different lengths so it cannot be a rectangular character array.
댓글 수: 0
Walter Roberson
2012년 11월 6일
Similar to strtok() is to use regexp() with the 'split' option. After getting the input from the user (e.g., questdlg() or a uicontrol() editbox),
theWords = regexp(S, 'split');
Just as with allwords(), theWords will be a cell array.
Note that theWords(1) would be a cell array containing a string, rather than the string itself. theWords{1} would be the string.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!