How do I print only one element of a char array with same elements?

So, here is the very simple practice code:
clear all
close all
clc
x=1:20;
for i=1:20
if x(i)<=5
say=('Hi')
elseif x(i)>5 && x(i)<=10
say=('Hello')
elseif x(i)>10 && x(i)<=15
say=('How is it going?')
else
say=('Fine')
end
end
I am new to Matlab and I got stuck on a simple point where I need to print any of the answers only once. I know that I'm gonna get 4 different answers 5 times each, but I want to get only one of each answer. One which will stand for the rest of the same answers. For example, just: 'Hi', 'Hello', 'How is it going', 'Fine' instead of getting each of them 5 times. Thanks in advance!
say =
Hi
say =
Hi
say =
Hi
say =
Hi
say =
Hi
say =
Hello
say =
Hello
say =
Hello
say =
Hello
say =
Hello
say =
How is it going?
say =
How is it going?
say =
How is it going?
say =
How is it going?
say =
How is it going?
say =
Fine
say =
Fine
say =
Fine
say =
Fine
say =
Fine
>>

回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 9 日

1 投票

x=1:20;
[test1,test2,test3,test4]=deal(0)
for i=1:20
if x(i)<=5 & test1==0
say=('Hi')
test1=1;
elseif x(i)>5 && x(i)<=10 & test2==0
say=('Hello')
test2=1;
elseif x(i)>10 && x(i)<=15 & test3==0
say=('How is it going?')
test3=1;
elseif test4==0
say=('Fine')
test4=1;
end
end

3 件のコメント

Mardan Tahmazli
Mardan Tahmazli 2016 年 7 月 10 日
oh I see. Does it mean that when you assign test# = 1, it breaks?
if x(i)<=5 & test1==0
say=('Hi')
test1=1;
So basically I can put anything here, right? Like if it was y=5 first, and then y=6.
x=1:20;
y=5
for i=1:20
if x(i)<=5 & y==5
say=('Hi')
y=6;
elseif x(i)>5 && x(i)<=10 & y==6
say=('Hello')
y=7;
elseif x(i)>10 && x(i)<=15 & y==7
say=('How is it going?')
y=8;
elseif y==8
say=('Fine')
y=9;
end
end
Thank you very much! It is all clear for me now.
Mardan Tahmazli
Mardan Tahmazli 2016 年 7 月 10 日
But definitely your method is much better than the one I posted now. Because it might be that the conditions are met in another order, not successively. Then my bit of code will not work. Thank you again!
Mardan Tahmazli
Mardan Tahmazli 2016 年 7 月 10 日
Sorry, I got stuck again, because in my code where I tried to apply this method, my requirement is to run it 8000 times, and I need all 8000 iterations. But as soon as I assign task=1, it breaks and it will not continue anymore..is there any other solution I can use? would appreciate a lot!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2016 年 7 月 9 日

コメント済み:

2016 年 7 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by