Matlab 如何将可变长度的单元格字符串数组作为函数的输入参数处理
我有一个函数,它可以在一个绘图上绘制多个系列,给定一个表头列表作为系列。我不确定如何解释一个参数点中的变量输入,该参数点接受字符串或字符串单元格数组,具体取决于序列的具体分解方式。例如,这样称呼它Matlab 如何将可变长度的单元格字符串数组作为函数的输入参数处理,matlab,plot,cell-array,Matlab,Plot,Cell Array,我有一个函数,它可以在一个绘图上绘制多个系列,给定一个表头列表作为系列。我不确定如何解释一个参数点中的变量输入,该参数点接受字符串或字符串单元格数组,具体取决于序列的具体分解方式。例如,这样称呼它 table2multiseries(myTable, 'Xvals', 'Yvals', 'name'); 将绘制x对y,其中每个系列都有不同的名称,即“John”、“Rob”等 也可以使用系列名称的单元格数组调用它,如下所示: table2multiseries(myTable, 'Xvals',
table2multiseries(myTable, 'Xvals', 'Yvals', 'name');
将绘制x对y,其中每个系列都有不同的名称,即“John”、“Rob”等
也可以使用系列名称的单元格数组调用它,如下所示:
table2multiseries(myTable, 'Xvals', 'Yvals', {'name', 'trial'});
这将绘制x对y,其中每个系列都有不同的名称和试用号,即“John-1”、“John-2”、“Rob-1”、“Rob-2”等
这就是代码,其中有一个if
语句,该语句当前解释了sName
为1、2或3个字符串。毫无疑问,这是一个黑客工作,因为它会重复3次。我想知道如何简化它以处理任意长度的序列名称标准输入。有什么想法吗
function figHandle = table2multiseries(tb, xName, yName, sName)
figHandle = figure;
hold on;
sList = unique(tb{:, sName}, 'rows');
if ischar(sName)
for k = 1:length(sList)
iRows = tb{:, sName}==sList(k,1);
leg{sList==s} = [sName ' ' num2str(s)];
tbtemp = tb(iRows, :);
tbtemp = sortrows(tbtemp, xName);
plot(tbtemp{:, xName}, tbtemp{:, yName}, '-o')
end
elseif iscellstr(sName) && length(sName)==2
for k = 1:length(sList)
iRows = tb{:, sName{1}}==sList(k,1) & tb{:, sName{2}}==sList(k,2)
leg{k,1} = [sName{1} ' ' num2str(sList(k,1)) ' - ' sName{2} ' ' num2str(sList(k,2)) ];
tbtemp = tb(iRows ,:);
tbtemp = sortrows(tbtemp, xName);
plot(tbtemp{:, xName}, tbtemp{:, yName}, '-o')
end
elseif iscellstr(sName) && length(sName)==3
for k = 1:length(sList)
iRows = tb{:, sName{1}}==sList(k,1) & tb{:, sName{2}}==sList(k,2) & tb{:, sName{3}}==sList(k,3);
leg{k,1} = [sName{1} ' ' num2str(sList(k,1)) ' - ' sName{2} ' ' num2str(sList(k,2)) ' - ' sName{3} ' ' num2str(sList(k,3)) ];
tbtemp = tb(iRows, :);
tbtemp = sortrows(tbtemp, xName);
plot(tbtemp{:, xName}, tbtemp{:, yName}, '-o')
end
end
title(tb.Properties.Description)
legend(leg);
end
您可以尝试使用嵌套for循环。这可能不够有效,但我认为在这种情况下这不会是一个问题。您可以尝试使用嵌套for循环。这可能不够有效,但我认为在这种情况下这不会是一个问题。