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

 Akzeptierte Antwort

madhan ravi
madhan ravi am 7 Dez. 2018
Bearbeitet: madhan ravi am 7 Dez. 2018

1 Stimme

a = 1;
n = 2; % just an example n
a = [zeros(1,n) a]

2 Kommentare

fyza affandi
fyza affandi am 7 Dez. 2018
Thank you very much :)
madhan ravi
madhan ravi am 7 Dez. 2018
Bearbeitet: madhan ravi am 7 Dez. 2018

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 7 Dez. 2018

3 Stimmen

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 Kommentare

madhan ravi
madhan ravi am 7 Dez. 2018
+1 shows many ways :-)
fyza affandi
fyza affandi am 7 Dez. 2018
Thank you very much
Glad you like it. Thanks for the vote. In that spirit, here is another one-liner way of doing it if you have the Image Processing Toolbox:
a = padarray(a, [0, n], 'pre')
It basically prepends n zeros to the beginning of array a.
Stephen23
Stephen23 am 7 Dez. 2018
Bearbeitet: Stephen23 am 7 Dez. 2018
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 am 2 Jan. 2019
Bearbeitet: Stephan am 2 Jan. 2019
49996 +2

Melden Sie sich an, um zu kommentieren.

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by