0

I have 60 different strings (Book01, Book02, ..., Book60). I want to do a certain procedure only for Book045 until Book58.

How do I write an if statement, so that the procedure is only performed for any String Book045 until Book58? For example:

Book48
    If (name of string = Book045 to Book58)
      My Procedure
    else
      Nothing
    end

Thanks.

1
  • If all names are of the type 'Book###', you could get the index of the book simply with str2double(), and then just test that the index is in your range. Commented Jan 7, 2021 at 12:47

1 Answer 1

3

If you have the names in a cell array

books = {'Book01', 'Book02', ..., 'Book59', 'Book60'};

Then you can extract the value in each name and check on that in your loop

for ii = 1:numel(books)
    val = erase( books{ii}, 'Book' ); % Remove the 'Book' prefix
    val = str2double( val );          % Convert to number
    if val >= 45 && val <= 58
        % do something in this range
    end 
end
Sign up to request clarification or add additional context in comments.

6 Comments

Wolfie, you were right. I got confused about his dataset, I thought that it contains characters instead of a string. Upvoted yours. Thank you for your feedback.
@Wolfie. Brilliant! This is perfectly right for what I asked, but please excuse me for not having been to clear or inaccurate, but what if all the books are character arrays. (For example Book01 is a 1x202040 char.) I understand that I should change the code like so: books = {Book01, Book02, ..., Book59, Book60};, but how to adapt the rest of your solution to fit this? Thanks again.
You could do books = strsplit(books, 'Book') to create the cell array first, then you wouldn't even need the erase.
@Wolfie. Thanks for helping me, but I think the answer might be simpler? What if the answer could be as simple as something like this: if Book == Book45|Book46|Book47|Book48|Book49|Book50|Book51|Book52|Book53|Book54|Book54|Book56|Book57|Book58 My Procedure end? I just need this if function to work? What am I dong wrong in this? Thanks for the trouble.
You've not made it clear in your question what your data types are or how you're looping over them. Without that info, my suggestion is the most robust thing I can suggest. The option you've put in the comment won't work because it's unclear what Book and BookXX are? They aren't in quotes like strings or chars, == won't work with chars, etc. Please edit your question or ask a new (and improved) one including a minimal reproducible example
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.