How to make a vector whose size can vary ?

조회 수: 4 (최근 30일)
charu shree
charu shree 2023년 4월 28일
이동: Matt J 2023년 4월 29일
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

답변 (1개)

Suraj
Suraj 2023년 4월 28일
이동: Matt J 2023년 4월 29일
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
Dyuman Joshi
Dyuman Joshi 2023년 4월 28일
이동: Matt J 2023년 4월 29일
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 2023년 4월 28일
이동: Matt J 2023년 4월 29일
Thank you suraj sir for to the point answer...
Also thanks a lot dyuman sir...

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by