How do I declare a blank column vector of unknown size?

조회 수: 115 (최근 30일)
Mohit Kumar
Mohit Kumar 2021년 11월 16일
답변: Mohit Kumar 2021년 11월 16일
I need to declare a column vector whose elements will be determined as the code runs. How do I declare such a vector of size n (entered by user) in MATLAB.
Thanks and Regards

채택된 답변

KSSV
KSSV 2021년 11월 16일
편집: KSSV 2021년 11월 16일
O = zeros(n,1) ; % Initiate a zeros column vector
N = NaN(n,1) ; % initiate a NaN column vector
iwant = zeros([],1) ; % empty vector which can be filled if length is not known

추가 답변 (2개)

Walter Roberson
Walter Roberson 2021년 11월 16일
MATLAB does not offer any way of creating blank column vectors of unknown size.
Any numeric column must have some numeric value assigned to the entries. If you write out numeric data to an Excel file, then NaN values will show up empty.
MATLAB allow you to create empty columns. However, if you write data further down in the column, the emptiness is filled with numeric 0 for numeric or logical columns, and by the character with binary value 0 for character columns.
A = repmat('', 5, 1)
A = 0×0 empty char array
A(5,1) = 'Z'
A = 5×1 char array
' ' ' ' ' ' ' ' 'Z'
double(A(1,1))
ans = 0
A(1,1) == ' '
ans = logical
0
The display of the expanded array makes it look like blanks were put in, but you can see that they are binary 0 instead.
Generally speaking, if you have not created a numeric column yet, and at some point in the program you find out how large it will be, then you can create it as the needed size using zeros() or ones() or inf() or nan() . For example,
NumRows = 4
NumRows = 4
B = ones(NumRows, 2, 'uint8')
B = 4×2
1 1 1 1 1 1 1 1
If you have not created a character column yet, and at some point in the program you find out how large it will be, then repmat() can sometimes be the easiest way to fill it with blanks:
NumRows = 4
NumRows = 4
NumCols = 7
NumCols = 7
C = repmat(' ', NumRows, NumCols)
C = 4×7 char array
' ' ' ' ' ' ' '
C(1,1) == ' '
ans = logical
1
and here you can see this gives true blanks.

Mohit Kumar
Mohit Kumar 2021년 11월 16일
Thanks to both of you. Your responses were helpful.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by