Asked by Matthew Moynihan
on 20 Jan 2011

If I wanted to create a matrix of blanks spaces I would use the following command:

A = [' ', ' '; ' ', ' ';];

but what if I do not know the length or width of the matrix? If the matrix was for ints or double types it would be easy:

A = zeros(column_number, row_number);

Is there a command that does the same thing as the zeros command but for characters?

Answer by Sean de Wolski
on 20 Jan 2011

Accepted Answer

You could use repmat:

repmat(' ',[3 3])

Walter Roberson
on 20 Jan 2011

Also,

char(' ' + zeros(column_number,row_number))

Jan
on 28 Jun 2012

Accepted by JSimon

Patrik Ek
on 23 Jan 2014

Sign in to comment.

Answer by Kenneth Eaton
on 20 Jan 2011

If you are only making a 1-D matrix (i.e. a row or column vector) then the function BLANKS is the way to go:

blankStr = blanks(4); % Makes a string of 4 blanks

For a 2-D matrix, the REPMAT-based solution from Sean de is probably the simplest, but here's another variant using the functions RESHAPE and BLANKS:

blankMat = reshape(blanks(4),2,2); % Makes a 2-by-2 matrix of blanks

Sign in to comment.

Answer by Hy
on 20 Jan 2011

There is not a command for characters that is analogous to zeros. Common commands for initializing matrices of size M x N (where sz = M*N) include

- those for doubles and singles: zeros(sz), ones(sz), nan(sz), inf(sz)
- those for logicals: true(sz), false(sz)
- those for cells: cell(sz)

The function blanks will produce a row vector. It is convenient because it avoids including a literal space character in your code, but specifying your choice of whitespace character and considering Locale Settings may produce clearer code.

Please note that because MATLAB uses column-major order [Wikipedia], I think that your example syntax should read

A = zeros(number_of_rows, number_of_columns);

The solutions by Sean and Kenneth can be restated using this syntax as:

sz = [number_of_rows, number_of_columns];

A = reshape(blanks(prod(sz)), sz);

B = repmat(' ', sz);

display(isequal(A,B));

All of these solutions work equally well to produce arrays of dimension 1, 2, ... n.

Walter Roberson
on 20 Jan 2011

Hy
on 21 Jan 2011

Updated answer to reflect Walter's correction.

Sign in to comment.

Answer by Malcolm Lidierth
on 21 Jan 2011

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.