How to add/append column in an array in a for loop?

Hello, I want to get the array [25 25 25 25 25] as the end value of Batt. However, the loop overwrites and I get [25 25 25]. I can't seem to figure out how to append the n_EVs(2) from the next column.
n_AGs = 2;
n_EVs = [2 3];
for j=1:n_AGs
Batt(1,1:n_EVs(j)) = 25;
end
I specifically want to take the value of n_EVs from the array at each iteration and append the Batt at each iteration. For example:
In the first iteration it should give [25 25]. The second iteration should give [25 25 25 25 25] after appending [0 0 25 25 25] to [25 25].
Would appreciate any help. Best!

 Respuesta aceptada

Image Analyst
Image Analyst el 24 de Dic. de 2018
Editada: Image Analyst el 24 de Dic. de 2018
Does this do what you want:
n_EVs = [2 3];
n_AGs = length(n_EVs)
Batt = [];
for k = 1 : n_AGs
Batt = [Batt, 25 * ones(1, n_EVs(k))]
end
Output:
n_AGs =
2
Batt =
25 25
Batt =
25 25 25 25 25
And for n_EVs = [2, 3, 5] it gives:
Batt =
25 25
Batt =
25 25 25 25 25
Batt =
25 25 25 25 25 25 25 25 25 25

Más respuestas (1)

madhan ravi
madhan ravi el 24 de Dic. de 2018
Editada: madhan ravi el 24 de Dic. de 2018
simply without loop:
Batt=repmat(25,1,sum(n_EVs))
%or
Batt=repelem(25,1,sum(n_EVs))
%or
Batt(1:5)=25;
If you want to stick with a loop then:
Batt=zeros(1,sum(n_EVs));
for i = 1:sum(n_EVs) % pfcourse you need to preallocate
Batt(i)=25; % just use linear indexing
end
Note: you only get three elements because your loop runs only till 2 not 5

5 comentarios

Saad
Saad el 24 de Dic. de 2018
I specifically want to take the value of n_EVs from the array at each iteration and append the Batt at each iteration. My apologies for not being to the point earlier.
madhan ravi
madhan ravi el 24 de Dic. de 2018
just give an example of your desired output
Saad
Saad el 24 de Dic. de 2018
Editada: madhan ravi el 24 de Dic. de 2018
In the first iteration it should give [25 25]. The second iteration should give [25 25 25 25 25] after appending [0 0 25 25 25] to [25 25] .
madhan ravi
madhan ravi el 24 de Dic. de 2018
Editada: madhan ravi el 24 de Dic. de 2018
Alright try this:
n_EVs = [2 3];
Batt=zeros(1,sum(n_EVs)); % you need to preallocate
n_AGs = 2;
blabla=[n_EVs(1) sum(n_EVs)];
for i = 1:numel(n_EVs)
Batt(1:blabla(i))=25 % just use linear indexing
end
Saad
Saad el 24 de Dic. de 2018
It'll work if n_AGs = 2; but if I change n_AGs = 3; or more it gives error.
For example if I change n_AGs = 3; and n_EVs = [2 3 5];

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 24 de Dic. de 2018

Comentada:

el 25 de Dic. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by