How to make a vector whose size can vary ?

8 views (last 30 days)
charu shree
charu shree on 28 Apr 2023
Moved: Matt J on 29 Apr 2023
Hello all , In the algorithm on which I am working, I need to have a vector whose size can vary in the for loop.
For e.g., In the below code I want to have bu_length to change to new dimension in each slot.
But the problem I am facing is that the new buffer length (bu_length_new) is still same as old buffer length (bu_length_old), only its contents are changed depending on "binornd".
Any help in this regard will be highly appreciated.
T = 20; % total slots
maxsize = 10; % maximum size of buffer
nodes = 8;
bu_length_old = zeros(maxsize,nodes); % This creates a buffer for each node and length is 10
n = 100; % number of packets
p = 0.2; % arrival rate of packets
for t = 1:T % each time slot
for i = 1:nodes
bu_length_new = qu_length(:,i)+ binornd(100,0.2);
end
end

Answers (1)

Suraj
Suraj on 28 Apr 2023
Moved: Matt J on 29 Apr 2023
A slight modification to the code will let you append a new column to bu_length_new with every iteration.
T = 20; % total slots
maxsize = 10; % maximum size of buffer
nodes = 8;
bu_length_old = zeros(maxsize,nodes); % This creates a buffer for each node and length is 10
n = 100; % number of packets
p = 0.2; % arrival rate of packets
for t = 1:T % each time slot
for i = 1:nodes
bu_length_new(:,i) = qu_length(:,i) + binornd(100,0.2);
end
end
bu_length_new is now a variable whose size varies. However, it is worth noting that vectors with variable sizes can cause significant overhead, and pre-allocating the variable is a good practice.
Hope this helps.
  2 Comments
Dyuman Joshi
Dyuman Joshi on 28 Apr 2023
Moved: Matt J on 29 Apr 2023
Is the "qu_length" supposed to be "bu_length"?
"For e.g., In the below code I want to have bu_length to change to new dimension in each slot."
Do you want to store the result of iteration in a new row/column? If yes, then refer to Suraj's comment above.
If not, please specify what you want to achieve, if possible, with an example.
charu shree
charu shree on 28 Apr 2023
Moved: Matt J on 29 Apr 2023
Thank you suraj sir for to the point answer...
Also thanks a lot dyuman sir...

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!