将结构元素作为参数输入到 matlab plot() 中

input structure elements into matlab plot() as arguments

我有 20-40 个离散图形要创建并保存在 Matlab 程序中。我正在尝试创建一个函数,该函数允许我输入元素(图像、线条、向量等)并通过将每个元素传递给 for 循环中的 plot() 来创建分层图:

function [  ] = constructFigs( figTitle, backgroundClass, varargin )

fig = figure('visible', 'off');

if strcmp(backgroundClass, 'plot') == 1

    plot(varargin{1});

elseif strcmp(backgroundClass, 'image') == 1

    imshow(varargin{1});

end


for i = 1:length(varargin)

    hold on

    if ndims(varargin{i}) == 2

        plot(varargin{i}(:, 1), varargin{i}(:, 2))

    else

        plot(varargin{i});

    end

end

saveas(fig, figTitle);

close(fig);

end

此功能有效,但在可以绘制的内容方面非常有限;您不能执行某些类型的绘图操作(例如叠加图像),也不能将可选参数传递给 plot()。我想做的是传入要绘制的元素结构,然后将这些结构元素作为参数传递给 plot() 。例如(简化且语法错误):

toBePlotted = struct('arg1', {image}, 'arg2', {vector1, vector2, 'o'})


    plot(toBePlotted.arg1)
    plot(toBePlotted.arg2)

我能够以编程方式构造具有参数名称的结构,但我无法以 plot 接受它们作为参数的方式从结构中提取元素。

如有任何帮助,我们将不胜感激

对于您的用例,您需要使用单元格扩展 {:} 来填充绘图的输入

plot(toBePlotted.arg1{:})
plot(toBePlotted.arg2{:})

这会将元胞数组 toBePlotted.arg1 中包含的元素扩展为 plot 的单独输入参数。

另一种选择是使用 line 而不是 plot(较低级别的图形对象)并向构造函数传递一个更易于理解的结构,其中包含您想要使用的所有参数对于那个情节。

s = struct('XData', [1,2,3], 'YData', [4,5,6], 'Marker', 'o', 'LineStyle', 'none');
line(s)

老实说,在您的程序本身内进行绘图可能比使用单独的函数要容易得多,因为您的函数中没有使用很多自定义参数。

如果你真的想要一些简化的绘图,你可以可以做这样的事情:

function plotMyStuff(varargin)

    fig = figure();
    hold on;

    for k = 1:numel(varargin)

        params = rmfield(varargin{k}, 'type');

        switch lower(varargin{k}.type)
            case 'line'
                line(params);
            case 'image'
                imagesc(params);
            otherwise
                disp('Not supported')
                return
        end 
    end

    saveas(fig);
    delete(fig);
end

plotMyStuff(struct('XData', [1,2], 'YData', [2,3], 'type', 'line'), ...
            struct('CData', rand(10), 'type', 'image'));