matlab gui处理未知矩阵大小

时间:2015-05-20 22:58:56

标签: matlab user-interface for-loop matrix handle

我现在正在编写一个GUI,其中包含一个加载矩阵的按钮:

function Load_Profile_Callback(hObject, eventdata, handles)
% hObject    handle to Load_Profile (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[FileName PathName] = uigetfile('*.mat','MATLAB Files');
handles.matrix=importdata([PathName FileName]);

接下来,我想将此矩阵的每一列定义为不同的通道,例如:

handles.Ch01Gr01=handles.matrix.Data(:,2);
handles.Ch01Gr02=handles.matrix.Data(:,3);
handles.Ch01Gr03=handles.matrix.Data(:,4);
handles.Ch01Gr04=handles.matrix.Data(:,5);
handles.Ch01Gr05=handles.matrix.Data(:,6);
handles.Ch01Gr06=handles.matrix.Data(:,7);
handles.Ch01Gr07=handles.matrix.Data(:,8);

如果我不知道这个矩阵中有多少列, 有什么选择可以在for loop中解决这个问题(或者任何其他想法也会很好)在这个矩阵维度上运行吗?

2 个答案:

答案 0 :(得分:0)

您可以在进入循环之前检查列数,然后根据循环索引创建动态字段(Check here)。

下面是一个示例GUI,其中按下按钮会导致加载矩阵A(魔法4x4矩阵...... A = magic(4)),我将其存储在文件' A.mat&#中39 ;.

function LoadDataGUI
clc
clear
hfigure = figure('Position',[200 200 100 100]);

handles.LoadButton = uicontrol('Style','push','Position',[50 50 50 20],'String','Load','Callback',@(s,e) LoadDataCllbck);

guidata(hfigure,handles);

    function LoadDataCllbck

        handles = guidata(hfigure);

        %// Load matrix. A is actually a magic(4) matrix.
        handles.Data = load('A.mat');

        %// Check # of columns
        NumCol = size(handles.Data.A,2);

        for k = 2:NumCol

            %// Create dynamic field name
            CurrField = sprintf('Ch01Gr%i',k-1);

            %// Assign it to the handles structure.
            handles.(CurrField) = handles.Data.A(:,k);

        end

        guidata(hfigure,handles);
    end

end

在这里,CurrField在每次迭代时都是这样的:

CurrField =

Ch01Gr1


CurrField =

Ch01Gr2


CurrField =

Ch01Gr3

您可以根据需要自定义格式sprintf

按下按钮后,这是handles结构的内容:

       LoadButton: 329.0085
          Data: [1x1 struct]
       Ch01Gr1: [4x1 double]
       Ch01Gr2: [4x1 double]
       Ch01Gr3: [4x1 double]

不要忘记预先分配内存的良好做法,特别是如果您的数据很大。

希望有所帮助!

答案 1 :(得分:0)

您可以为channel创建一个单元格数组:

numch = size(handles.matrix, 2);
for i = 1:numch
    handles.Ch01Gr{i} = handles.matrix.Data(:, i);
end