How to write a script to fill vector

조회 수: 4 (최근 30일)
Anthony
Anthony 2012년 10월 15일
답변: Ananya Tewari 2020년 6월 18일
Write a script to fill vector b defined by b = {x for x<1 & x^2 for 1≤x≤4 & 16 for x>4}
First fill in vector x from 0 to 5 in intervals of 0.5 and then using a for loop with if, elseif and/or else statements, fill in vector b based on x as specified above. Print the value of b when finished.

답변 (1개)

Ananya Tewari
Ananya Tewari 2020년 6월 18일
Hi,
I understand that you want to create a vector b with the conditions as defined using for / if / else statements.
There are two ways to create the vector b as specified.
%way 1 using loop and other statements
x = [0:0.5:5.0]
b = [];
for i=1:numel(x)
if(x(i)<1)
b = [b,x];
elseif(x(i)>=1 && x(i)<=4)
b = [b,x(i)^2];
else
b = [b,4];
end
end
b
%way 2
x = [0:0.5:5.0];
b = [X(X<1), (X(X>=1 & X<=4)).^2 ];
k = x(x>4);
k(:,:) = 4;
b = [b,k]

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by