# How to assign strings and numbers to elements of the same matrix?

59 views (last 30 days)

Show older comments

I want to write the word "average" in the 5 element, first row on my matrix and I want to write numbers 1 to 3 into the second to fourth elements. But I am using wrong syntax:

ResultMtx(2:5,1) = [1; 2; 3; "average"];

How can I write this correctly? Thank you.

##### 0 Comments

### Accepted Answer

Walter Roberson
on 9 Sep 2021

[1; 2; 3; "average"]

The first part of that, the 1; 2; 3, is establishing a numeric array -- in particular a double precision array.

The last part of that, the "average", is a string() scalar.

MATLAB cannot store string() scalars inside a numeric array. MATLAB numeric arrays do not store the datatype of each element separately: numeric arrays only store a single datatype that applies to the entire array.

You can create a cell array,

ResultMatx = num2cell(ResultMatx);

ResultMatx(2:5,1) = {1; 2; 3; "average"};

cell arrays can have a different datatype for each element. But you might not like the formatting for displaying them.

##### 3 Comments

Walter Roberson
on 9 Sep 2021

### More Answers (1)

Steven Lord
on 9 Sep 2021

Do you need your data stored with mixed-type columns or would mixed-type rows work? If the latter, consider a table array.

ResultTbl = table(1, 2, 3, "average")

scores = ResultTbl{1, 1:3}

assessment = ResultTbl.Var4

##### 2 Comments

Hassan Bahy
on 20 Nov 2021

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!