i am confused with commands for loop

조회 수: 1 (최근 30일)
Hend Nasrallah
Hend Nasrallah 2021년 6월 8일
댓글: Rena Berman 2021년 6월 29일
Write MATLAB code including loop to look for first zero item in a randomly given vector (1 column and 10 rows). You need to include the generation of this random values vector in the code as well, the random values must be generated between 0 and 10. The search result should be associated with text: 'The zero is found in' and then state the element v(i,1) :
Otherwise, if it is not found, include a text : 'The zero item is not found '.
  댓글 수: 2
dpb
dpb 2021년 6월 8일
So, what have you tried and where, specifically, did you get stuck?
Did you look up documentation and see examples on random numbers, looping "for...end", etc., etc., etc., ...
Rena Berman
Rena Berman 2021년 6월 29일

(Answers Dev) Restored edit

댓글을 달려면 로그인하십시오.

답변 (2개)

Kunal Kandhari
Kunal Kandhari 2021년 6월 8일
To create an array of random numbers between range 0 to 10 with size (10,1):
arr=randi(11,1,10)-1;
% first parameter is range ie., 1-11
%second parameter is number of columns
% third parameter is number of rows
% We want random array between range 0-10 therefore we have substracted 1
% at end from all elements
For more detail about this function you can refer:
For looping over array:
for i=1:length(arr)
end
For more detail about for loop you can refer:
Complete code for this question:
arr=randi(11,1,10)-1;
index=0;
%this index indicates that no 0's are found
disp(arr);
%print whole array, you can remove this line
for i=1:length(arr)
if(arr(i)==0)
%if array element is 0, store its position in index field and break
%loop
index=i;
break;
end
end
% if index is zero then no 0's are found and id index is not zero then 0 is
% present in array at position index
if(index==0)
disp("The zero item is not found ");
else
disp("The zero is found in arr("+index+",1)");
end
Output screenshot:
  댓글 수: 2
Kunal Kandhari
Kunal Kandhari 2021년 6월 8일
James Tursa
James Tursa 2021년 6월 8일
@Kunal Kandhari We discourage posting complete answers to homework questions.

댓글을 달려면 로그인하십시오.


Sambit Supriya Dash
Sambit Supriya Dash 2021년 6월 8일
r = (randi([0 10],1,10))';
r0 = r == 0;
if sum(r0) == 0
disp('Zero is not found')
else
for i = 1:length(r)
if r(i) == 0
fprintf('Zero is found in %.0f \n',i)
break
else
end
end
end
  댓글 수: 2
dpb
dpb 2021년 6월 8일
@Sambit -- note James' comment above -- best practice is to coach and answer specific syntax or similar questions, but it doesn't help the poster much to do their homework for them...
Sambit Supriya Dash
Sambit Supriya Dash 2021년 6월 9일
편집: Sambit Supriya Dash 2021년 6월 9일
I'll take care to find further it's a homework question or genuine question some is interested to solve. Thank You

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by