MATLAB: Perform “For-loop or IF-statement” only for specific character arrays

[亡魂溺海] 提交于 2021-01-29 11:20:24

问题


I have 60 different character arrays (Book01, Book02, ..., Book60). (For example Book01 is a 1x202040 char.). I want to do a certain procedure only on Book45 until Book58.

How do I write an IF-statement or FOR-loop, so that the procedure is only performed for character arrays Book45 until Book58? For example:

Book05  % Inserted Array for test

if Book45|Book46|Book47|Book48|Book49|Book50|Book51|Book52|Book53|Book54|Book54|Book56|Book57|Book58 % If inserted array is Book45-58     
   % Procedure to be performed on "Inserted Array", only if Book45-58    
else
   % No Procedure on Book01-44 or Book59-60
end

Thanks


回答1:


as mentioned in the comment, better to put all arrays into one big array. If you insist on calling a particular array you can write:

 for ii=45:58
     a=eval(['Book' num2str(ii)]); % 
     % Procedure to be performed on a
 end

but everywhere I see to try and avoid eval...




回答2:


I'm just putting the comment in an answer, so I can write some code. I actually lost my matlab license yesterday, so cannot test it.

for i = 1:[largest book number]
    book = eval(['Book' num2str(i)]);
    if i >= 45 && i <= 58
        % procedure for book45 until and including book58
    else
        % procedure for other books
    end
end

IMHO the only reason not to use eval is because it is slow (and possibly error prone), but in this case it's not an issue. But instead of having all these separate arrays, you could put all books in a cell array and drop the eval.

edit: but now I read that you have "No Procedure on Book01-44 or Book59-60". If the else statement is empty, then the answer by dpdp is fully sufficient.



来源:https://stackoverflow.com/questions/65639018/matlab-perform-for-loop-or-if-statement-only-for-specific-character-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!