This question is closed. Reopen it to edit or answer.

How to store a data by getting from for loop in matlab ?

1 view (last 30 days)
Arul prasath
Arul prasath on 24 Nov 2014
Closed: MATLAB Answer Bot on 20 Aug 2021
For example i'm getting value like this
a=[192.1225 60.2626 0.9993 100.3275];
for 'n' number of iteration, which means i will get so many values like
a=[192.1225 60.2626 0.9993 100.3275];
a=[20.1225 66.2626 1.0 10.8775];
a=[2.0925 64.2626 1.0 110.5475]; .....
it will continues like this and it will stop based on the 'for loop'
and now i want to store all the 'a' values in 'b' like this
b=[192.1225 60.2626 0.9993 100.3275
20.1225 66.2626 1.0 10.8775
2.0925 64.2626 1.0 110.5475];
and again the same value should display like this
p=[192.1225 60.2626 0.9993 100.3275];
q=[20.1225 66.2626 1.0 10.8775];
r=[2.0925 64.2626 1.0 110.5475]; .....

Answers (2)

Adam on 24 Nov 2014
If you know how many columns a is going to have and how many rows your final result will have (presumably you do if it is in a for loop) then you don't need the intermediate 'a' result at all.
Just pre-declare b as e.g
b = zeros( n, 4 );
for i = 1:n
b( i, : ) = yourCalculation();
where n is obviously however many rows you intends to have.
Stephen on 25 Nov 2014
+1 for starting the code with array-preallocation.

Orion on 24 Nov 2014
Edited: Orion on 24 Nov 2014
it's basic concatenation
for i=1:n
% some calculation
a = % your new row vector
then you get a matrix b, and you just have to rerieve the line that interests you.
l = b(2,:);
Arul prasath
Arul prasath on 24 Nov 2014
ya. but sir, you just run the code once again and type capital 'X' in command window and similarly Capital 'Y' after executing that you will get the position on 'Cluster head (CH)' so at final i want only those values with energy and distance.
For example
CH=[164.9445 90.7746 0.9996 65.5964]
in this first two values represents 'X' and 'Y' and remaining are energy and distance.

Community Treasure Hunt

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

Start Hunting!