0
votes

I wrote a code that replaces non-numeric values in the matrix by some number. Now, to test it I would like to allow MATLAB to accept non-numeric entries.

My code starts with prompt: matrix_input = input('Please enter the matrix: x=');

If I enter something like [1,2,3;4,5,?], MATLAB gives an error: Unbalanced or unexpected parenthesis or bracket. Since all brackets seem to be balanced, I assume this is due to non-numeric entry. Is it possible to make MATLAB allow non-numeric entries?

1
Use NaN there to replace those non-numeric entries?Divakar
@Divakar, I already have a code for makeing replacements. My problem is I cannot test it on a matrix with non-numeric entry. I also do not know what character will be used to test my code performance: perhaps '?' or may be something elseuser3349993
Try a cell instead of a matrix. You can put pretty much anything in a cell. c = {1, 2, 3; 4, 5, '?'}. From there you can do replacements and get a matrix with m = cell2mat(c).Nras
What are you trying to do with this matrix? Give the rest of your use case so we can better help.Peter

1 Answers

4
votes

You need a cell array. Each cell of a cell array can hold any type of data. Curly braces are used to create a cell array like this:

cell_array = {1, 2, 3; '4', '?', 6};

If you use regular braces to access an element in a cell array you get a cell. If you use curly braces you get the contents of the cell. It's this difference that tends to catch people out with cell arrays.

cell_array(1) % Returns a 1x1 cell containing the value 1.
cell_array{1} % Returns 1

EDIT

Out of curiosity, what code are you using to replace the non-numeric values? For a cell array I came up wit the following:

idx = cellfun(@isnumeric, cell_array);
cell_array(~idx) = {NaN};
matrix = cell2mat(cell_array);

As mentioned in the comments, you could also use a struct array:

struct_array = struct('v', {1, 2, 3; '4', '?', 6});

This would create an array of structures where the field v contains the value. However, I can't think of a neat way to perform the replacement at the minute.