MATLAB Answers


Simple if statement question

Asked by JP
on 19 Jun 2013

Hi, just getting the hang of the basics of MATLAB and had a quick easy question. I have a variable defined as a string and I want to use an if statement on two parts of the string seperately.


Astr = '123456789'

if Astr(2:4,5:7) == '234','567'

    x = 5

Of course I am hoping x = 5 would appear when I run this, but it gets an error on the 'if' line. Let me know how to accomplish this!



No products are associated with this question.

2 Answers

Answer by the cyclist
on 19 Jun 2013
Edited by the cyclist
on 19 Jun 2013
 Accepted answer

You are pretty much inventing your own syntax here, and MATLAB won't understand that. :-)

One way to perform this test is

Astr = '123456789'
if strcmp(Astr(2:4),'234') && strcmp(Astr(5:7),'567')
    x = 5;

The string comparison command that I used here is better than using "==" (which is more appropriate for numeric comparisons).

  1 Comment

on 19 Jun 2013

Or shorter, use strcmp(Astr([2:4,5:7]), '234567' )

Answer by JP
on 19 Jun 2013

Thanks very much! Yes I figured I was inventing a few things when doing that haha


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!