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

input structure elements into matlab plot() as arguments

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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()。例如(简体且语法错误):

1
2
3
4
5
toBePlotted = struct('arg1', {image}, 'arg2', {vector1, vector2, 'o'})


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

我能够以编程方式构造带有参数名称的结构,但是我无法从结构中提取元素,以使绘图将其作为参数。

任何帮助将不胜感激


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

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

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

另一个选择是使用line而不是plot(较低级别的图形对象),并向构造函数传递一个更易懂的结构,该结构包含您要用于该绘图的所有参数。 >

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

不过,说实话,在程序中进行绘制可能比拥有单独的函数容易得多,因为函数中没有使用很多自定义参数。

如果您真的想要一些简化的绘图,则可以执行以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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'));