How to repeat the first number only

조회 수: 3 (최근 30일)
fyza affandi
fyza affandi 2018년 12월 7일
편집: Stephan 2019년 1월 2일
Array a is given
a =[1]
How can I add 0 to the array depending on n.
n=1 --> a=[0 1]
n=2 --> a=[0 0 1]
n=3 --> a=[0 0 0 1]
and n can be changes to any number

채택된 답변

madhan ravi
madhan ravi 2018년 12월 7일
편집: madhan ravi 2018년 12월 7일
a = 1;
n = 2; % just an example n
a = [zeros(1,n) a]
  댓글 수: 2
fyza affandi
fyza affandi 2018년 12월 7일
Thank you very much :)
madhan ravi
madhan ravi 2018년 12월 7일
편집: madhan ravi 2018년 12월 7일

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

추가 답변 (1개)

Image Analyst
Image Analyst 2018년 12월 7일
madhan's way is the best (how I'd do it), but I just want to show you a neat trick - that you can "grow" an array by simply assigning something to the last location (the location at the largest point that you want to grow it to):
a = 1; % Initial array.
n = 2; % just an example n
% a = [zeros(1,n) a] % Best way
a(n+1) = 0; % Enlarge array by appending zeros simply by assigning the last element.
a = fliplr(a) % Flipr it so that the 1 is on the right.
  댓글 수: 5
Stephen23
Stephen23 2018년 12월 7일
편집: Stephen23 2018년 12월 7일
Not just a neat trick, until R2015b allocating to the last element (and implicitly filling array with zeros) was faster than calling zeros:
Stephan
Stephan 2019년 1월 2일
편집: Stephan 2019년 1월 2일
49996 +2

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by