How to create a categorical variable with a specified number of characters?

조회 수: 3 (최근 30일)
Hi, I am trying to create a vector called 'labels' which has 1883 'N's followed by 332 'A's. The code I am currently using just gives a string of N's and A's like this:
NNNNNNNAAAAAAA
However, I wanted to create a variable called 'labels' which has 2215 (2883 + 332) rows and 1 column like this:
[N; N; N; N; .... A; A; A]
Any help would be much appreciated, thanks in advance
% create a categorical variable with 1883 'N's' and 332 'A's'
labels(1:1883) = 'N';
labels(1884:2215) = 'A';

채택된 답변

Stephen23
Stephen23 2020년 12월 26일
편집: Stephen23 2020년 12월 27일
labels = [repmat('N',1883,1);repmat('A',332,1)];
or less robustly:
labels( 1:1883,1) = 'N';
labels(1884:2215,1) = 'A';
% ^^ added
  댓글 수: 3
Cai Chin
Cai Chin 2020년 12월 26일
Also, when I use the summary function, it gives this error: Check for missing argument or incorrect argument data type in call to function 'summary'. However, I would like it to say:
A 332
N 1883
Stephen23
Stephen23 2020년 12월 27일
"however, each letter seems to have an apostrophe before it like this: 'A. How can I resolve this?"
labels = [repmat('N',8,1);repmat('A',3,1)]
labels = 11x1 char array
'N' 'N' 'N' 'N' 'N' 'N' 'N' 'N' 'A' 'A' 'A'
The single-quote is simply an artifact of how MATLAB displays character arrays (i.e. it tells us that the data have type char) it is not part of the data itself. If you do not want to display the data within single-quotes then you can write your own display routine based on FPRINTF or similar.
"Also, when I use the summary function, it gives this error: Check for missing argument or incorrect argument data type in call to function 'summary'."
The summary function is not specified to work on character arrays, it is defined to work on table classes, which is why you get that error. My guess is that you actually want something like this:
T = table(categorical(cellstr(labels)));
summary(T)
Variables: Var1: 11x1 categorical Values: A 3 N 8

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Categorical Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by