【问题标题】:How to assign a matrix to a cell of a cell array如何将矩阵分配给元胞数组的一个元胞
【发布时间】:2018-06-22 03:13:44
【问题描述】:

我正在使用 matlab 并尝试将矩阵分配给元胞数组的一个元胞。然而,总是有什么不对劲。代码如下:

    C = {};
    myMatrix = xlsread('myexcelfile');
    C{'ID', 'info'} = myMatrix;

然后matlab提示说

“预计大括号或点索引表达式有一个输出,但有 12 个结果。”

但是如果我不使用“ID”和“Info”,而是使用“1”和“2”,则矩阵可以分配成功。

谁能帮帮我?谢谢!

【问题讨论】:

  • 那你为什么不使用C{1,2} = myMatrix? (或您需要的任何数字,而不是 1、2)您想要达到什么结果?
  • @LuisMendo 我想获得一个数组,每当我输入用户的姓名和ID时,我都可以获得相应的信息,该信息存储在一个矩阵中。这就是为什么我必须使用字符串而不是数字。
  • 如果您想按名称索引,您可能需要table,而不是元胞数组。元胞数组使用数字或逻辑索引。 (它们可以用字符索引,但这并没有给出你想要的结果)。查看一些索引到表的示例here
  • @LuisMendo 好的。谢谢你。也许我应该尝试另一种方式。

标签: matlab matrix cell-array


【解决方案1】:

假设我们有三个人,每个人都有一个姓名和身份证号,每个人对应的数据大小是2x3。我使用一个单元格来存储数据并通过随机数填充它。(在你的情况下,你应该使用xlsread('myexcelfile') 来填充这个单元格)。每个 ID 号都与一个字符串连接,因为 Matlab 不接受直接由数字转换的字符串,用于表的行和列中的名称。

clc;clear all;close all;
%  assuming we have got three persons in the dataset 
cell_data=cell(3,3); % I use cell instead of matrix for storing data
ID_number=[38;48;58];% this vector contains the ID numbers of each person

for i=1:numel(ID_number);rng('shuffle');cell_data{i,i}=rand(2,3);end % using  random number as dataset 

ID=strcat('ID ',string(ID_number));%'38' is not a valid variable name so concat number with 'ID ' string 
Customer = string({'Jones';'Brown';'Smith'});
Customer = cellstr(Customer);
T = table('RowNames',Customer); 
for i=1:numel(ID_number)
T.(char(ID(i)))=cell_data(:,i);
end
% 

创建表格后,我们可以得到如下输入:

input_cell = inputdlg({'Name','ID number'});% 2x1 cell

ID_input=strcat('ID ',input_cell{2,1});

T( {input_cell{1,1}} , {ID_input} )

如果输入格式适应表格,我们可以得到这样的输出:

  table

             ID48    
         ____________

Brown    [2×3 double]

对于输入不适应表格格式的情况,您可以在脚本中添加一些条件。

【讨论】:

    猜你喜欢
    • 2014-10-07
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多