How to print the value of a variable after every round in matlab? - matlab

I have 100 nodes using following for loop:
xm1=100; %diameters of sensor network
ym1=100;
sink1.x=50; %distance of base station from the network
sink1.y=120;
nl = 100; %no of nodes
pl=0.1; %probibilty of a node to become cluster head
El1= 0;
Eint=0.5; %energy supplied to each node
Etl =0 ;
for i=1:1:nl
Sl(i).xd=rand(1,1)*xm1; %it will distribute the nodes in 1 dimension in x axis randomly.
XR(i)=Sl(i).xd; %we store its value in xr
Sl(i).yd=rand(1,1)*ym1; %it will distribute the nodes in 1 dimension in y axis randomly
YR(i)=Sl(i).yd;
Sl(i).id = i;
Sl(i).G=0; % as the no of node that have been cluster head is zero 0
Sl(i).E=Eint; %%*(1+rand*a);
%fprintf(' Sensor node energy: %15f \n',Eint); %?
%initially there are no cluster heads only nodes
Sl(i).type='N';
end
cluster formation took place like tis
for r=1:1:rmax
for i=1:1:nl
if(Sl(i).E>0)
temp_randl=rand;
if ( (Sl(i).G)<=0)
if(temp_randl<= (pl/(1-pl*mod(r,round(1/pl)))))
countCHsl=countCHsl+1;
packets_TO_BSl=packets_TO_BSl+1;
PACKETS_TO_BSl(r+1)=packets_TO_BSl;
Sl(i).type='C';
Sl(i).G=round(1/pl)-1;
Cl(clusterl).xd=Sl(i).xd;
Cl(clusterl).yd=Sl(i).yd;
distancel=sqrt( (Sl(i).xd-(Sl(n+1).xd) )^2 + (Sl(i).yd-(Sl(n+1).yd) )^2 );
Cl(clusterl).distance=distancel;
Cl(clusterl).id=i;
X(clusterl)=Sl(i).xd;
Y(clusterl)=Sl(i).yd;
clusterl=clusterl+1;
distancel;
if (distancel>do)
Sl(i).E=Sl(i).E- ( (ETX+EDA)*(4000) + Emp*4000*(distancel*distancel*distancel*distancel ));
end
if (distancel<=do)
Sl(i).E=Sl(i).E- ( (ETX+EDA)*(4000) + Efs*4000*(distancel * distancel ));
end
end
end
% S(i).G=S(i).G-1;
end
end
STATISTICS.COUNTCHS(r+1)=countCHsl;
for i=1:1:nl
if ( Sl(i).type=='N' && Sl(i).E>0 )
if(clusterl-1>=1)
min_disl=Inf;
min_dis_clusterl=0;
for cl=1:1:clusterl-1
templ=min(min_disl,sqrt( (Sl(i).xd-Cl(cl).xd)^2 + (Sl(i).yd-Cl(cl).yd)^2 ) );
if ( templ<min_disl )
min_disl=templ;
min_dis_clusterl=cl;
end
end
min_disl;
if (min_disl>do)
Sl(i).E=Sl(i).E- ( ETX*(4000) + Emp*4000*( min_disl *min_disl * min_disl * min_disl));
end
if (min_disl<=do)
Sl(i).E=Sl(i).E- ( ETX*(4000) + Efs*4000*( min_disl * min_disl));
end
Sl(Cl(min_dis_clusterl).id).E =Sl(Cl(min_dis_clusterl).id).E- ( (ERX + EDA)*4000 );
packets_TO_CHl=packets_TO_CHl+1;
Sl(i).min_disl=min_disl;
Sl(i).min_dis_clusterl=min_dis_clusterl;
else
min_disl=sqrt( (Sl(i).xd-Sl(n+1).xd)^2 + (Sl(i).yd-Sl(n+1).yd)^2 );
if (min_disl>do)
Sl(i).E=Sl(i).E- ( ETX*(4000) + Emp*4000*( min_dis1 *min_dis1 * min_dis1 * min_dis1));
end
if (min_disl<=do)
Sl(i).E=Sl(i).E- ( ETX*(4000) + Efs*4000*( min_disl * min_disl));
end
packets_TO_BSl=packets_TO_BSl+1;
end
end
end
end
Now I have to print value of S1(i).E for all i after every round?
Means I have to print remaining energy of all nodes at every round.
Thanks in advance.
And the exact answer of this question is
fprintf('%0.2f \n',Sl(:).E);

I assume r stands for round, so you could add any of the following lines right before your last end to print the remaining energy:
sprintf('%0.2f \n',Sl(:).E);
disp([Sl(:).E]');
Sl(:).E

a simple
S1(i).E,
should work.

Related

NetLogo addition of nominal values giving unusual results

When a variable is being incremented by very small value (say 0.01), it is not giving proper (precise) results as expected.
Looking for suggestions(if any) to deal with the same.
globals[p]
to go
set p 0
while[p <= 1]
[
print p
set p p + 0.01
]
end
First read this:
http://floating-point-gui.de/
Then to subdivide an interval into n pieces, do this:
to-report subdivide [#xmin #xmax #n]
let ps n-values (#n + 1) [? / #n]
report map [#xmin + ? * (#xmax - #xmin)] ps
end

Matlab: two different variables take the same value

I want to implement recursion without a recursive function.
My code is the following:
for ff=1:6
for step=i:-1:1
if (step == maxStep)
R=-1;
if(isTM =='1')
R =1;
end
else
DielectricConst =cell2mat(valueArray(step,1));
Magnetic =cell2mat(valueArray(step,2));
currentFreq = cell2mat(frequencies(ff));
w = 2*3.1416*currentFreq;
kiz =w*(DielectricConst*Magnetic - E0*M0*sin(angle).*sin(angle))^(1/2);
DiConstPlusOne = cell2mat(valueArray(step+1,1));
MagPlusOne =cell2mat( valueArray(step+1,2));
kizPlusOne =w*(DiConstPlusOne*MagPlusOne - E0*M0*sin(angle).*sin(angle))^(1/2);
res =((DiConstPlusOne*kiz)-(DielectricConst*kizPlusOne))/((DiConstPlusOne*kiz)+(DielectricConst*kizPlusOne));
result =(res + R * exp(-((-1)^(1/2))*2*kizPlusOne*cell2mat( valueArray(step+1,3))))/(1+res*(R)*exp(-((-1)^(1/2))*2*kizPlusOne*cell2mat( valueArray(step+1,3))));
R=result;
end
% disp(R);
end
end
res and result values are always the same. Is it a pointer problem ?

Scilab Storing Into Array [Channel Coding]

This is part of my codes
e=0;
c=0;
n=10000;
for t=zeros(1:n)
//state1
x=rand();
if(x<=0.95) then disp(t);
c=c+1;
elseif(x>0.95)
//state2
x=rand();
if(x<=0.99) then disp(t)
c=c+1;
//state3
elseif(x>0.99) then disp(t=1)
e=e+1;
arr(e)=t; //store error bits only
end
end
end
disp(c);
disp(e);
for z=1:e //loop the earlier arr(s)
disp(arr(z)) //display all arr of s
end
clear();
What I was trying to do is to generate 10000 of zeros.
Out of these 10000 zeros, there will be few with errors meaning to say for example I might get 9990 of zeros and 10 of ones.
Currently, I have made an array storing only the ones. Now I'm abit lost on how do I store both zeros and ones into the same array.
Let say, current running..I will end up with 10 of ones (Those zeros that contains error bit). Then at this part of the code, all the zeros that has turned into ones will be stored into arr(e). Therefore the output would be
0
0
0
0
0
0
0
0
0
0
But what i wanted is something like this.
arr[1] = 0
.
.
.
arr[250] = 1
.
.
.
arr[749] = 1
.
.
.
arr[1234] = 1
.
.
.
arr[5463] = 1
.
.
.
arr[6678] = 1
.
.
.
arr[8890] = 1
.
.
.
arr[9987] = 1
.
.
.
arr[10000] = 0
Which shows the error bit occur at 250,749,1234,5463,6678,8890,9987
Thank you
All you have to do is:
e = [250 759 1234 5463 6678 8890 9987];
arr = zeros(10000,1);
arr(e) = 1;
e defines where you want the values in arr to be changed to 1. You simply just use e to index into arr and set the corresponding positions to 1. That's it... nothing really to it!

Simulation in verilog using $monitor

I've been trying to implement full adder in Verilog. I have implemented it and it is also showing results on Isim. Only problem is that when I try to see the simulation using $monitor command, it is showing me only 1 result, not all simulation results. Here is testbench code:
module Full_adder_s2_testbench;
// Inputs
reg a;
reg b;
reg cin;
// Outputs
wire sum;
wire cout;
// Instantiate the Unit Under Test (UUT)
Full_adder_s2 uut (
.a(a),
.b(b),
.cin(cin),
.sum(sum),
.cout(cout)
);
integer i;
initial begin
// Initialize Inputs
a = 0;
b = 0;
cin = 0;
// Wait 100 ns for global reset to finish
#100;
end
always # ( a, b, cin )
begin
// generate truth table
for ( i = 0; i < 8; i = i + 1 )
// every 10 ns set a, b, and cin to the binary rep. of i
#10 {a, b, cin} = i;
$monitor( "%d ns: a + b + cin = %b + %b + %b = cout sum = %b %b",
$time, a, b, cin, cout, sum );
// stop 10ns after last change of inputs
#10 $stop;
end
endmodule
And here is result in ISIM:
# run 1000 ns
Simulator is doing circuit initialization process.
Finished circuit initialization process.
400 ns: a + b + cin = 1 + 1 + 1 = cout sum = 1 1
Stopped at time : 410 ns : in File "E:/Namal/FYP/My work/XILINX/Full_adder_s2/Full_adder_s2_testbench.v" Line 66
$monitor is only meant to be setup once and will trigger every time a signal changes, try using $display since you already have the statement inside of your always #*.
While learning Verilog I would encourage you to use begin end liberally. The issue is that only 1 line was in the for loop, the $display/$monitor was outside and so only executed once at the start.
always #* begin
// generate truth table
for ( i = 0; i < 8; i = i + 1 ) begin //<-- Added begin
// every 10 ns set a, b, and cin to the binary rep. of i
#10 {a, b, cin} = i;
$display( "%d ns: a + b + cin = %b + %b + %b = cout sum = %b %b", $time, a, b, cin, cout, sum );
end //<--Added end
// stop 10ns after last input
#10 $stop;
end
Full example on EDA Playground.
NB: it is best not to use manual sensitivity lists any more replace always # ( a, b, cin ) with always #*. This will result in quicker refactoring and lowering the chance of RTL to gates simulation mismatch.

MATLAB Execution Time Increasing

Here is my code. The intent is I have a Wireshark capture saved to a particularly formatted text file. The MATLAB code is supposed to go through the Packets, dissect them for different protocols, and then make tables based on those protocols. I currently have this programmed for ETHERNET/IP/UDP/MODBUS. In this case, it creates a column in MBTable each time it encounters a new register value, and each time it comes across a change to that register value, it updates the value in that line of the table. The first column of MBTable is time, the registers start with the second column.
MBTable is preallocated to over 100,000 Rows (nol is very large), 10 columns before this code is executed. The actual data from a file I'm pulling into the table gets to about 10,000 rows and 4 columns and the code execution is so slow I have to stop it. The tic/toc value is calculated every 1000 rows and continues to increase exponentially with every iteration. It is a large loop, but I can't see where anything is growing in such a way that it would cause it to run slower with each iteration.
All variables get initialized up top (left out to lessen amount of code.
The variables eth, eth.ip, eth.ip.udp, and eth.ip.udp.modbus are all of type struct as is eth.header and eth.ip.header. WSID is a file ID from a .txt file opened earlier.
MBTable = zeros(nol,10);
tval = tic;
while not(feof(WSID))
packline = packline + 1;
fl = fl + 1;
%Get the next line from the file
MBLine = fgetl(WSID);
%Make sure line is not blank or short
if length(MBLine) >= 3
%Split the line into 1. Line no, 2. Data, 3. ASCII
%MBAll = strsplit(MBLine,' ');
%First line of new packet, if headers included
if strcmp(MBLine(1:3),'No.')
newpack = true;
newtime = false;
newdata = false;
stoppack = false;
packline = 1;
end
%If packet has headers, 2nd line contains timestamp
if newpack
Ordered = false;
if packline == 2;
newtime = true;
%MBstrs = strsplit(MBAll{2},' ');
packno = int32(str2double(MBLine(1:8)));
t = str2double(MBLine(9:20));
et = t - lastt;
if lastt > 0 && et > 0
L = L + 1;
MBTable(L,1) = t;
end
%newpack = false;
end
if packline > 3
dataline = int16(str2double(MBLine(1:4)));
packdata = strcat(packdata,MBLine(7:53));
end
end
else
%if t >= st
if packline > 3
stoppack = true;
newpack = false;
end
if stoppack
invalid = false;
%eth = struct;
eth.pack = packdata(~isspace(packdata));
eth.length = length(eth.pack);
%Dissect the packet data
eth.stbyte = 1;
eth.ebyte = eth.length;
eth.header.stbyte = 1;
eth.header.ebyte = 28;
%Ethernet Packet Data
eth.header.pack = eth.pack(eth.stbyte:eth.stbyte+27);
eth.header.dest = eth.header.pack(eth.header.stbyte:eth.header.stbyte + 11);
eth.header.src = eth.header.pack(eth.header.stbyte + 12:eth.header.stbyte + 23);
eth.typecode = eth.header.pack(eth.header.stbyte + 24:eth.header.ebyte);
if strcmp(eth.typecode,'0800')
eth.type = 'IP';
%eth.ip = struct;
%IP Packet Data
eth.ip.stbyte = eth.header.ebyte + 1;
eth.ip.ver = eth.pack(eth.ip.stbyte);
%IP Header length
eth.ip.header.length = 4*int8(str2double(eth.pack(eth.ip.stbyte+1)));
eth.ip.header.ebyte = eth.ip.stbyte + eth.ip.header.length - 1;
%Differentiated Services Field
eth.ip.DSF = eth.pack(eth.ip.stbyte + 2:eth.ip.stbyte + 3);
%Total IP Packet Length
eth.ip.length = hex2dec(eth.pack(eth.ip.stbyte+4:eth.ip.stbyte+7));
eth.ip.ebyte = eth.ip.stbyte + max(eth.ip.length,46) - 1;
eth.ip.pack = eth.pack(eth.ip.stbyte:eth.ip.ebyte);
eth.ip.ID = eth.pack(eth.ip.stbyte+8:eth.ip.stbyte+11);
eth.ip.flags = eth.pack(eth.ip.stbyte+12:eth.ip.stbyte+13);
eth.ip.fragoff = eth.pack(eth.ip.stbyte+14:eth.ip.stbyte+15);
%Time to Live
eth.ip.ttl = hex2dec(eth.pack(eth.ip.stbyte+16:eth.ip.stbyte+17));
eth.ip.typecode = eth.pack(eth.ip.stbyte+18:eth.ip.stbyte+19);
eth.ip.checksum = eth.pack(eth.ip.stbyte+20:eth.ip.stbyte+23);
%eth.ip.src = eth.pack(eth.ip.stbyte+24:eth.ip.stbyte+31);
eth.ip.src = ...
[num2str(hex2dec(eth.pack(eth.ip.stbyte+24:eth.ip.stbyte+25))),'.', ...
num2str(hex2dec(eth.pack(eth.ip.stbyte+26:eth.ip.stbyte+27))),'.', ...
num2str(hex2dec(eth.pack(eth.ip.stbyte+28:eth.ip.stbyte+29))),'.', ...
num2str(hex2dec(eth.pack(eth.ip.stbyte+30:eth.ip.stbyte+31)))];
eth.ip.dest = ...
[num2str(hex2dec(eth.pack(eth.ip.stbyte+32:eth.ip.stbyte+33))),'.', ...
num2str(hex2dec(eth.pack(eth.ip.stbyte+34:eth.ip.stbyte+35))),'.', ...
num2str(hex2dec(eth.pack(eth.ip.stbyte+36:eth.ip.stbyte+37))),'.', ...
num2str(hex2dec(eth.pack(eth.ip.stbyte+38:eth.ip.stbyte+39)))];
if strcmp(eth.ip.typecode,'11')
eth.ip.type = 'UDP';
eth.ip.udp.stbyte = eth.ip.stbyte + 40;
eth.ip.udp.src = hex2dec(eth.pack(eth.ip.udp.stbyte:eth.ip.udp.stbyte + 3));
eth.ip.udp.dest = hex2dec(eth.pack(eth.ip.udp.stbyte+4:eth.ip.udp.stbyte+7));
eth.ip.udp.length = hex2dec(eth.pack(eth.ip.udp.stbyte+8:eth.ip.udp.stbyte+11));
eth.ip.udp.checksum = eth.pack(eth.ip.udp.stbyte+12:eth.ip.udp.stbyte+15);
eth.ip.udp.protoID = eth.pack(eth.ip.udp.stbyte+20:eth.ip.udp.stbyte+23);
if strcmp(eth.ip.udp.protoID,'0000')
eth.ip.udp.proto = 'MODBUS';
%eth.ip.udp.modbus = struct;
eth.ip.udp.modbus.stbyte = eth.ip.udp.stbyte+16;
eth.ip.udp.modbus.transID = eth.pack(eth.ip.udp.modbus.stbyte:eth.ip.udp.modbus.stbyte+3);
eth.ip.udp.modbus.protoID = eth.ip.udp.protoID;
eth.ip.udp.modbus.length = int16(str2double(eth.pack(eth.ip.udp.modbus.stbyte + 8:eth.ip.udp.modbus.stbyte + 11)));
eth.ip.udp.modbus.UID = eth.pack(eth.ip.udp.modbus.stbyte + 12:eth.ip.udp.modbus.stbyte + 13);
eth.ip.udp.modbus.func = hex2dec(eth.pack(eth.ip.udp.modbus.stbyte + 14:eth.ip.udp.modbus.stbyte+15));
eth.ip.udp.modbus.register = eth.pack(eth.ip.udp.modbus.stbyte + 16: eth.ip.udp.modbus.stbyte+19);
%Number of words to a register, or the number of registers
eth.ip.udp.modbus.words = hex2dec(eth.pack(eth.ip.udp.modbus.stbyte+20:eth.ip.udp.modbus.stbyte+23));
eth.ip.udp.modbus.bytes = hex2dec(eth.pack(eth.ip.udp.modbus.stbyte+24:eth.ip.udp.modbus.stbyte+25));
eth.ip.udp.modbus.data = eth.pack(eth.ip.udp.modbus.stbyte + 26:eth.ip.udp.modbus.stbyte + 26 + 2*eth.ip.udp.modbus.bytes - 1);
%If func 16 or 23, loop through data/registers and add to table
if eth.ip.udp.modbus.func == 16 || eth.ip.udp.modbus.func == 23
stp = eth.ip.udp.modbus.bytes*2/eth.ip.udp.modbus.words;
for n = 1:stp:eth.ip.udp.modbus.bytes*2;
%Check for existence of register as a key?
if ~isKey(MBMap,eth.ip.udp.modbus.register)
MBCol = MBCol + 1;
MBMap(eth.ip.udp.modbus.register) = MBCol;
end
MBTable(L,MBCol) = hex2dec(eth.ip.udp.modbus.data(n:n+stp-1));
eth.ip.udp.modbus.register = dec2hex(hex2dec(eth.ip.udp.modbus.register)+1);
end
lastt = t;
end
%If func 4, make sure it is the response, then put
%data into table for register column
elseif false
%need code to handle serial to UDP conversion box
else
invalid = true;
end
else
invalid = true;
end
else
invalid = true;
end
if ~invalid
end
end
%end
end
%Display Progress
if int64(fl/1000)*1000 == fl
for x = 1:length(mess);
fprintf('\b');
end
%fprintf('Lines parsed: %i',fl);
mess = sprintf('Lines parsed: %i / %i',fl,nol);
fprintf('%s',mess);
%Check execution time - getting slower:
%%{
ext = toc(tval);
mess = sprintf('\nExecution Time: %f\n',ext);
fprintf('%s',mess);
%%}
end
end
ext = toc - exst;
Update: I updated my code above to remove the overloaded operators (disp and lt were replaced with mess and lastt)
Was asked to use the profiler, so I limited to 2000 lines in the table (added && L >=2000 to the while loop) to limit the execution time, and here are the top results from the profiler:
SGAS_Wireshark_Parser_v0p7_fulleth 1 57.110 s 9.714 s
Strcat 9187 29.271 s 13.598 s
Blanks 9187 15.673 s 15.673 s
Uigetfile 1 12.226 s 0.009 s
uitools\private\uigetputfile_helper 1 12.212 s 0.031 s
FileChooser.FileChooser>FileChooser.show 1 12.085 s 0.006s
...er>FileChooser.showPeerAndBlockMATLAB 1 12.056 s 0.001s
...nChooser>FileOpenChooser.doShowDialog 1 12.049 s 12.049 s
hex2dec 44924 2.944 s 2.702 s
num2str 16336 1.139 s 0.550 s
str2double 17356 1.025 s 1.025 s
int2str 16336 0.589 s 0.589 s
fgetl 17356 0.488 s 0.488 s
dec2hex 6126 0.304 s 0.304 s
fliplr 44924 0.242 s 0.242 s
It appears to be strcat calls that are doing it. I only explicitly call strcat on one line. Are some of the other string manipulations I'm doing calling strcat indirectly?
Each loop should be calling strcat the same number of times though, so I still don't understand why it takes longer and longer the more it runs...
also, hex2dec is called a lot, but is not really affecting the time.
But anyway, are there any other methods I can use the combine the strings?
Here is the issue:
The string (an char array in MATLAB) packdata was being resized and reallocated over and over again. That's what was slowing down this code. I did the following steps:
I eliminated the redundant variable packdata and now only use eth.pack.
I preallocated eth.pack and a couple "helper variables" of known lengths by running blanks ONCE for each before the loop ever starts
eth.pack = blanks(604);
thisline = blanks(47);
smline = blanks(32);
(Note: 604 is the maximum possible size of packdata based on headers + MODBUS protocol)
Then I created a pointer variable to point to the location of the last char written to packdata.
pptr = 1;
...
dataline = int16(str2double(MBLine(1:4)));
thisline = MBLine(7:53); %Always 47 characters
smline = [thisline(~isspace(thisline)),blanks(32-sum(~isspace(thisline)))]; %Always 32 Characters
eth.pack(pptr:pptr+31) = smline;
pptr = pptr + 32;
The above was inside the 'if packline > 3' block in place of the 'packdata =' statement, then at the end of the 'if stoppack' block was the reset statement:
pptr = 1; %Reset Pointer
FYI, not surprisingly this brought out other flaws in my code which I've mostly fixed but still need to finish. Not a big issue now as this loop executes lightning fast with these changes. Thanks to Yvon for helping point me in the right direction.
I kept thinking my huge table, MBTable was the issue... but it had nothing to do with it.