필터 지우기
필터 지우기

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

조회 수: 74 (최근 30일)
Hannah
Hannah 2021년 9월 9일
댓글: Hassan Bahy 2021년 11월 20일
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.

채택된 답변

Walter Roberson
Walter Roberson 2021년 9월 9일
[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
Walter Roberson
Walter Roberson 2021년 9월 9일
I recommend you use cell arrays, and use writecell(), provided that your MATLAB is new enough to have writecell()
data = randi(9, 6, 1)
data = 6×1
4 3 8 8 1 7
datacell = num2cell(data);
datacell{end-1,1} = "average";
datacell{end,1} = mean(cell2mat(datacell(1:end-2,:)))
datacell = 6×1 cell array
{[ 4]} {[ 3]} {[ 8]} {[ 8]} {["average"]} {[ 5.7500]}
Walter Roberson
Walter Roberson 2021년 9월 9일
You could also use a numeric array and put NaN values, and then later ask to writecell into that particular location in the existing table. This is not efficient, as it requires a separate writecell() for each text written into an otherwise numeric column (though adjacent items could be merged into one call.)

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

추가 답변 (1개)

Steven Lord
Steven Lord 2021년 9월 9일
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")
ResultTbl = 1×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ _________ 1 2 3 "average"
scores = ResultTbl{1, 1:3}
scores = 1×3
1 2 3
assessment = ResultTbl.Var4
assessment = "average"
  댓글 수: 2
Walter Roberson
Walter Roberson 2021년 9월 9일
If I understand correctly, user is looking to store the results into Excel, not unlike the way it is common for people to have spreadsheets that say things like
Jan 5
Feb 2
Mar -4
Apr 7
total ====
10
Hassan Bahy
Hassan Bahy 2021년 11월 20일
mr Walter Roberson could you help me to create a table consist of multi rows with two column the first column from data type string & second column is numbers, could you help me sir,please

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by