Write a text string into a cell in a matrix

28 次查看(过去 30 天)
I have a matrix that is (100*4) dimension. All the entries of first three columns are all numerical values and the last column (nbr4) needs to be a text.
CR7=zeros(100,4);
for the first row; ( the values of each cell is selected manually).
CR7(1,1)=82;
CR7(1,2)=4;
CR7(1,3)=9.37;
CR7(1,4)={'AVG'};
When I tried to run it, I got an error: The following error occurred converting from cell to double: Error using double Conversion to double from cell is not possible." My objective here is to fill out all the elements of this matrix (100*4) using an " if, else" statement, so basically under certain condition, the elements of this matrix will be filled out from different matrices ( all numerical), expect the elements of the last column, they will always be either "AVG" or "Mrg". ( text/ string, not numerical.) Can anyone give some good advise please, I hope my explanation is a bit clear, I can share my code on here or via email, whichever is easier.
Thank you so much, Amine

回答(1 个)

Stephen23
Stephen23 2016-1-14
编辑:Stephen23 2016-1-15
You are confusing cell arrays and numeric arrays. The two are different array types, so when you try to mix them it causes an error.
In a nutshell:
  • A numeric array contains numeric data.
  • A cell array contains other arrays.
You basically have a choice for storing your data:
  1. Store the numeric values in a numeric array, and the strings in a cell array.
  2. Store a numeric code of the strings (i.e. a map), rather than the strings themselves.
  3. Store all of the values in a cell array.
I would recommend that you do pick the first or second option, as it will make processing and handling your data much much simpler than trying to access numeric data from inside a cell array. Really, avoid the third option. Either try this:
X = zeros(100,3); % numeric
Y = cell(100,1); % cell
X(1,1) = 82;
X(1,2) = 4;
X(1,3) = 9.37;
Y{1,1} = 'AVG';
Or this:
A = zeros(100,4); % numeric
map = {'AVG','Mrg'};
A(1,1) = 82;
A(1,2) = 4;
A(1,3) = 9.37;
A(1,4) = find(strcmp(map,'AVG'));
  2 个评论
Amine Ben Ayara
Amine Ben Ayara 2016-1-14
Stephen, Thank you so much for your help. I'm really new to Matlab so Im doing my best to learn. So I tried your code and I got a num matrix (100,3) for X and cell array vector (100,1) for Y. This : Y{1,4} = 'AVG'; transformed Y to 100*4 cell array matrix. My objective is to have X(100,*4) and all the 4th column entries are 'AVG', basically string cell array.
Stephen23
Stephen23 2016-1-15
编辑:Stephen23 2016-1-15
I fixed the indexing into the cell array, it should be {1,1}, not {1,4}.
As I explained in my answer, keeping numeric data in a cell array makes data processing more complicated, and I would recommend the first solution instead.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by