将给定的MATLAB字符串分解为多个节的数组

时间:2015-10-21 05:37:57

标签: matlab

假设我有以下字符串:

%%
a = 2
%% 
a =3
%%
t = 0:.1:pi*4;
y = sin(t);
for k = 3:2:9
    %%
    y = y + sin(k*t)/k;
    if ~mod(k,3)
        %%
        display(sprintf('When k = %.1f',k));
        plot(t,y)
    end
end

如果您注意到第三部分有嵌套部分。

我希望输出为

[ 'a = 2', 'a=3' , 't = 0:.1:pi*4; y = sin(t); for k = 3:2:9 %% y = y + sin(k*t)/k; if ~mod(k,3) %% display(sprintf('When k = %.1f',k)); plot(t,y) end end']

如何使用字符串操作实现此目的?

问题是使用普通的正则表达式,'%%'会将第3部分分成3个部分。

1 个答案:

答案 0 :(得分:1)

假设这背后的逻辑是你想要将任何循环或条件语句(forwhileif)放在一起,那么你可以检查' %%'但也要跟踪你进入和退出的循环/条件数。

如果你逐行浏览,那么代码将如下所示(变量tline是文本行):

% initialize counters
str_count = 0;
in_loop = 0;

% iterate through text lines
while (tline ~= -1)
    % check for the %% marker but only increment string counter if not in a loop
    if ~isempty(strfind(tline,'%%')) && (in_loop == 0);
        str_count = str_count + 1;
    else
        % if no %% or in a loop, add the current line to the current string
        str_set{str_count} = [str_set{str_count} tline];

        % check for "for", "if", or "while" and increment the loop counter if found
        if ~isempty(strfind(tline,'for ')) || ~isempty(strfind(tline,'if ')) || ~isempty(strfind(tline,'while '))
            in_loop = in_loop + 1;
        end
        % check for "end" and decrement the loop counter if found
        if ~isempty(strfind(tline,'end'));
            in_loop = in_loop - 1;
        end
    end
end

请注意,这会使用strfind来查找forwhileifend命令(前三个后有空格) )。但是,它也会拾取最后包含这些字符串的单词(例如,行xfor = 1;将被拾取)。因此,您要么必须添加一些额外的检查,要么注意如何命名变量 - 也许更好的方法是查找这些字符串是最好的。你应该在单词之前看到空格,除非它们是第一个单词,并且可以为这种效果添加条件。

相关问题