如何将 table 的值传递给矩阵

How to pass the value of a table to a matrix

我正在尝试在 matlab 中做一个 GUI,接受 table 中的值以将其转换为矩阵,但想法是用户可以先设置行数和列数。
面板看起来像这样
按钮的代码是

function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
rows =str2double(get(handles.edit_rows,'String'));
cols=str2double(get(handles.edit_cols,'String'));
num_elem=cell(rows,cols);
num_elem(:,:)={"};
set(handles.uitable1,'Data',num_elem)
set(handles.uitable1,'ColumnEditable',true(1,cols))

但是,如何导出或转换为矩阵以便我可以对其应用函数?

更新 在 byetisener 的帮助下,我将代码更新为 函数 pushbutton1_Callback(hObject、事件数据、句柄)

% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
filas=str2double(get(handles.edit_fila,'String'));
column=str2double(get(handles.edit_col,'String'));
num_elem=cell(filas,column);
num_elem(:,:)={''};
set(handles.uitable1,'Data',num_elem)
set(handles.uitable1,'ColumnEditable',true(1,column))
handles.uitable1.Data = cell(filas, column);
matrix = cell2mat(handles.uitable1.Data);
matrix

但这是一个空矩阵

它没有获取单元格的值,假设按钮调整大小并同时复制值,如果不是,如何在矩阵调整大小时复制到另一个按钮?

我不确定这是否回答了您的问题,但您可以按照此方法进行操作。

首先,如果您有兴趣,在 MATLAB 中使用点符号比 setter 和 getter 方法更快。

那么,您可以做的是:

handles.uitable1.Data = cell(rows, cols);

或者,当然,或者:

set(handles.uitable1, 'Data', cell(rows,cols));

如果你想将uitable中的数据转换为矩阵,你可以使用:

matrix = cell2mat(handles.uitable1.Data);

如果您 table 包含非数值:

tableData = handles.uitable1.Data;
tableData = [str2double(tableData(:, 1)), cell2mat(tableData(:, 2))];

希望这对您有所帮助。如果您解决了问题,请告诉我。

您的代码存在一些问题:

  1. 您实际上并没有在这里赋值,您只是将 uitable 的数据设置为一个空单元格数组。
num_elem =

  1×2 cell array

    {0×0 char}    {0×0 char}
  1. 如果您成功了,您的代码将只在 uitable 的第一列中写入您想要的所有内容。因为您没有遍历行。按钮仅添加到第一行。
  2. 如果 table 中有不同的数据类型,
  3. cell2mat() 函数将不起作用。您可能认为您没有不同的数据类型,但空单元格是单元格类型,您输入的数据是双精度类型,所以它就是这样。

为了解决所有这些问题,我为您重写了一个回调函数。您可以直接将此代码粘贴到您的回调中,替换您的回调。最后我应该给你你想要的矩阵,它在我的电脑里。

filas  = str2double(handles.edit_fila.String);
column = str2double(handles.edit_col.String);

% This loop looks for an empty row to write new data
for i = 1:length(handles.uitable1.Data) 
   if isempty(handles.uitable1.Data{i,1})
       handles.uitable1.Data(i,1) = {filas};
       handles.uitable1.Data(i,2) = {column};
       break;
   else
       disp('Error occured');
   end
end

% This double for loop check if there are any empty cells 
% if it finds one, it changes it to 0, so all the cells have the same type
for i = 1:length(handles.uitable1.Data) 
    for j = 1:2                         
        if isempty(handles.uitable1.Data{i,j})
            handles.uitable1.Data(i,j) = {0};
        else
            disp('Error occured');
        end
    end
end

matrix = cell2mat(handles.uitable1.Data); % The matrix you want

只需检查所有变量名称是否相同,不要忘记接受 is 作为答案。希望能帮助到你。