# If statement for a values in a string

4 Ansichten (letzte 30 Tage)
Andre am 31 Mai 2013
Iam a Matlab newbi, so need some help. Working on a for-loop. In the for-loop my if statement doesn't work as i wish. I want it to work like this: When the value of i= one of the numbers in the string, h, make a plot of the function f(i). So the problem is the first line in the if-statement.
h=[8 17 25 30 36 41 49 58]
for i=1:65
F(i)
if i= one of the values in the string defined above
plot F(i)
end
end
Any suggestions to fix this if-statement?
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Jonathan Sullivan am 31 Mai 2013
The variable h does appear to be a string, but rather a vector of doubles. What you want to use to determine if a scalar is equal to any element of a vector is the function ismember
Example
ismember(i,h)
Hope this helps.
##### 2 KommentareKeine anzeigenKeine ausblenden
Andre am 31 Mai 2013
Bearbeitet: Andre am 31 Mai 2013
Doesn't the ismember function only tell if its true or false?
I want my function to be plotted if i=one of the values in h. I don't want to know if i=one of the values i h or not.
Jan am 31 Mai 2013
@Andre: I do not understand the last paragraph of your comment.

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Jan am 31 Mai 2013
The most straight solution would be not to run the loop from 1 to 65, but:
h = [8 17 25 30 36 41 49 58]
for i = h
...
Now the loop runs through the elements of h only. If this does not matches your needs for any reasons, the suggested ismember is fine:
h = [8 17 25 30 36 41 49 58]
for i=1:65
F(i)
if ismember(i, h)
plot F(i)
end
end
This is leaner and faster:
if any(i == h)
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Andre am 1 Jun. 2013
I understand. Thanks to both of you for helping me out:)

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Axis Labels finden Sie in Help Center und File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by