I want to read bits from a file and then to convert them to complex double. Each number is 32 bits (16 Re and 16 Im). Then I want to use qamdemod to get 6 bits per one complex number and to save those bits in new text file.
I did that program but I always gets the same number as output 010011=50
that is the program:
% % Main Algorithm
N=16; %length of one sample
RUNTIME = input('How long you want to run in sec=');
prompt = '0 - for sequentially. 1 - for randomaly =';
n = input(prompt);
x=0;
switch n
case 0
timerID = tic; %# Start a clock and return the timer ID
disp('sequentially');
fid=fopen('rand.bin'); %need to check if file opened
fid_w=fopen('samples.txt','w'); %write to file
while true
%# Perform process
Re=fread(fid,N);
Re=Re'; %transpose to row vector
Im=fread(fid,N);
Im=Im'; %transpose to row vector
if size(Re)~=N
disp('Re is out of range');
break;
end
if size(Im)~=N
disp('Im is out of range');
break;
end
Re_dec=bi2de(Re);
Im_dec=bi2de(Im);
in = (Re_dec/65535) + (Im_dec*(1i)/65535); % unit circle 65535
double(in);
disp("IN:");
disp(in);
out = qamdemod(in,64);
data_out = de2bi(out);
disp(data_out);
fprintf(fid_w,'%f\n',in); %write to sample file
if (feof(fid))
disp('end of file');
break;
end
if(toc(timerID) > RUNTIME) %# Get the elapsed time for the timer
disp('end of time');
break;
end
end
case 1
disp('randomaly')
otherwise
disp('error')
end
fclose('all'); %close all open files
% out = lteSymbolDemodulate(in,'64QAM');
qamdemod was not working correctrly: the right code is:
% % Main Algorithm
RUNTIME = input('How long you want to run in sec=');
prompt = '0 - for sequentially. 1 - for randomaly =';
n = input(prompt);
x=0;
N=16;
fid=fopen('rand.bin'); %need to check if file opened
fid_w=fopen('samples.txt','w'); %write to file
switch n
case 0
disp('sequentially');
sequentially(fid,fid_w,RUNTIME); %call sequentially function
case 1
disp('randomaly');
randomaly(fid,fid_w,RUNTIME); %call randomaly function
otherwise
disp('Error: Wrong select')
end
fclose('all'); %close all open files
fid=fopen('samples.txt'); %need to check if file opened
digest=entropy(fid); %Creating entropy
disp(digest);
fclose('all'); %close all open files
function sequentially(fid,fid_w,RUNTIME)
N=16; %length of one sample
timerID = tic; %# Start a clock and return the timer ID
while true
%# Perform process
Re_bin=fread(fid,N);
if size(Re_bin')~=N
disp('Re is out of range');
break;
end
% disp("Re_bin=");
% disp(Re_bin');
Re=convert_to_number(Re_bin);
Im_bin=fread(fid,N);
if size(Im_bin')~=N
disp('Im is out of range');
break;
end
Im=convert_to_number(Im_bin);
in=complex(Re,Im);
% disp("IN:");
% disp(in);
out = conv_qam64(in);
% disp("OUT:");
% disp(out);
%%%%%%%% if want binary can use bin_out to convert %%%%%%%%%
% bin_out=dec2bin(out);
% disp("OUT BIN:");
% disp(bin_out);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf(fid_w,'%2.0f\n',out); %write to sample file
if (feof(fid))
% disp('end of file');
break;
end
if(toc(timerID) > RUNTIME) %# Get the elapsed time for the timer
% disp('end of time');
break;
end
end
% fclose('all'); %close all open files
Related
I am trying to parallelize the code below in matlab:
%reduce the size of A if necessary.
A=rand(100,60);
B=int8(rand(size(A,1),size(A,2))>0.5);
N=10;
G=15;
lambda_tol_vector= zeros(G,1);
conto = 1;
for h=-G:0.1:G
lambda_tol_vector(conto)=2^(h);
conto = conto+1;
end
M=4;
tol = 1e-9;
CompletedMat_nopar1={};
tic
for RIPETIZIONE = 1:10
%using normal for loop CompletedMat is saved
for k = 1:size(lambda_tol_vector,1)
%fprintf('Completion using nuclear norm regularization... \n');
%sequential code:
[CompletedMat34,flag] = matrix_completion_nuclear_GG_vec(A.*double(B),double(B),N,lambda_tol_vector(k),tol);
%parallel code thread-based:
if flag==1
CompletedMat_nopar1{RIPETIZIONE,k}=zeros(size(A));
end
CompletedMat_nopar1{RIPETIZIONE,k}=CompletedMat34;
end
end
toc
After having vectorized whereby possible I ended up with the following code:
A = parallel.pool.Constant(A);
lambda_tol_vector=parallel.pool.Constant(lambda_tol_vector);
R=10;
K=size(lambda_tol_vector.Value,1);
CompletedMat_parvec=cell(R,K);
idx=cellfun('isempty', CompletedMat_parvec);
CompletedMat_parvec(idx)={zeros(size(A.Value))};
B=double(B);
tic
parfor n=1:R*K
[~,k]=ind2sub([R,K],n);
%fprintf('Completion using nuclear norm regularization... \n');
[CompletedMat,flag] = matrix_completion_nuclear_GG_vec( ...
A.Value.*B,B, N, lambda_tol_vector.Value(k), tol);
if flag~=0
CompletedMat_parvec{n}=CompletedMat;
end
end
toc
The problem here is that CompletedMat_parvec and CompletedMat_nopar1 provide totally different results while they are expected to give the same result.
How is this possible?
For the sake of completeness I will provide matrix_completion_nuclear_GG_vec below:
%%
% We need a functional environment so that the MAtimesVec subfunction can
% access variables in workspace
function [Anew,objective,flag,iteration] = matrix_completion_nuclear_GG_vec(A,B,N,lambda_tol,tol)
%%
%This code ttries to vectorize and make more efficient the code in
%matrix_completion_nuclear_GG_alt
%% Singular value thresholding for structured (sparse + low rank) matrix
%clear;
%tol=10^-7;
%lambda_tol=0.5;
%%
% Read in sparse matrices downloaded from The University of Florida Sparse
% Matrix Collection
%data = load('mhd4800b.mat');
%A = data.mhd4800b;
%A=A(1:100,1:100);
%A=rand(100,5)*rand(5,100);
%[sA,vA,dA]=svd(A)
%%
% initialization
%B = rand(size(A))<0.3; % remove 10% of the entries
mat=A.*B;
m = size(mat,1);
n = size(mat,2);
L = zeros(m,1);
R = zeros(n,1);
iteration=0;
criterion=0;
flag=0;
Anew=L*R';
objective=zeros();
while (criterion==0 && iteration<N && flag==0)
Aold=Anew;
iteration=iteration+1;
%iteration
%%
% Generation of structured matrix (sparse plus low rank)
%LR = L*R'; % generation of low rank matrix
%Amat = mat + LR; % sparse + low rank
%%
% Find all singular values >= lambda_tol by svt (deflation method). Function
% MAtimesVec is defined at end of this file.
%tic;
%[u,s,v] = svt(#MAtimesVec,'m',m,'n',n,'lambda',lambda_tol);
[u,s,v] = svd(mat+Anew);
%toc;
%display(size(s));
if size(s,1)==0
Anew=NaN*A;
objective=NaN;
flag=1;
return
elseif max(max(s))<=lambda_tol
Anew=NaN*A;
objective=NaN;
flag=1;
return
else
for k=1:min(size(s,1),size(s,2))
if s(k,k)<lambda_tol
s(k,k)=0;
else
s(k,k)=s(k,k)-lambda_tol;
end
end
%size(s,1)
%s=s-lambda_tol*eye(size(s,1));
L=u*s;
R=v;
mat=(A-u*s*v').*B;
Anew=L*R';
objective(iteration)=1/2*(norm(mat,'Fro'))^2+lambda_tol*(sum(diag(s)));
%objective(iteration)
if (norm(Anew-Aold,'Fro')^2/(norm(Aold,'Fro')^2))<tol
criterion=1;
end
%norm(A-Anew,'Fro')
end
end
if flag==1
Anew=[];
objective=[];
end
%%
% Subfunction for exploiting matrix structure of sparse plus low rank
%function MAvec = MAtimesVec(vec, trans)
% if trans
% MAvec = (vec'*mat)' + R*(vec'*L)';
% else
% MAvec = mat*vec + L*(R'*vec);
% end
%end
end
%%%%%%%%%%%%%%%
%%%%%% Loop through data 3 ms at a time (Live)
t_window = 3e-3;
ind_3_raw = t_window*fs; %%% Number of samples for 3 ms in raw data
ind_3_spec = ceil(t_window/(T(2)-T(1))); %%%% Number of samples for 3 ms in spectrogram
counter = 0; %%%% number of 3 ms windows from start of file
stay_in = 1; %%% change to zero when its time to break;
figure(2);
while stay_in
%%%% Make time series and spectrogram plot
if (((counter+1)*ind_3_raw)<length(t)) %%%% if last point is outside of data
subplot(211)
plot(t(counter*ind_3_raw+1:(counter+1)*ind_3_raw)*1e3,data_filt((counter*ind_3_raw+1:(counter+1)*ind_3_raw)),'k')
% plot(t(counter*ind_3_raw+1:(counter+1)*ind_3_raw),data((counter*ind_3_raw+1:(counter+1)*ind_3_raw)),'k')
xlabel('Time [ms]')
ylabel('A.U.')
% xlim([0 t(end)])
set(gca,'fontsize',16)
subplot(212)
imagesc(T(counter*ind_3_spec+1:(counter+30)*ind_3_spec)*1e3,F/1000,S_dB(:,counter*ind_3_spec+1:(counter+30)*ind_3_spec));
% imagesc(T(counter*ind_3_spec+1:(counter+1)*ind_3_spec),F/1000,S_dB(:,counter*ind_3_spec+1:(counter+1)*ind_3_spec));
% imagesc(T(counter*ind_3_spec+1:(counter+1)*ind_3_spec),F/1000,Sf_dB(:,counter*ind_3_spec+1:(counter+1)*ind_3_spec));
axis xy;
xlabel('Time [ms]')
ylabel('Frequency [kHz]')
% colorbar
caxis([30 60])
% caxis([40 80]) %%% caxis limits, might need to change this manually when needed
% xlim([0 T(end)])
colormap jet
set(gca,'fontsize',16)
counter = counter + 1; %%% increment counter
drawnow;
pause;
%%%% Get user input
else
stay_in = 1;
end
end
I want a pop up dialog box for user to input a 1 every time a sferic in data appears?
I want to segment an Arabic word into single characters. Based on the histogram/profile, I assume that I can do the segmentation process by cut/segment the characters based on it's baseline (it have similar pixel values).
But, unfortunately, I still stuck to build the appropriate code, to make it works.
% Original Code by Soumyadeep Sinha
% Saving each single segmented character as one file
function [segm] = trysegment (a)
myFolder = 'D:\1. Thesis FINISH!!!\Data set\trial';
level = graythresh (a);
bw = im2bw (a, level);
b = imcomplement (bw);
i= padarray(b,[0 10]);
verticalProjection = sum(i, 1);
set(gcf, 'Name', 'Trying Segmentation for Cursive', 'NumberTitle', 'Off')
subplot(2, 2, 1);imshow(i);
subplot(2,2,3);
plot(verticalProjection, 'b-'); %histogram show by this code
% hist(reshape(input,[],3),1:max(input(:)));
grid on;
% % t = verticalProjection;
% % t(t==0) = inf;
% % mayukh = min(t)
% 0 where there is background, 1 where there are letters
letterLocations = verticalProjection > 0;
% Find Rising and falling edges
d = diff(letterLocations);
startingColumns = find(d>0);
endingColumns = find(d<0);
% Extract each region
y=1;
for k = 1 : length(startingColumns)
% Get sub image of just one character...
subImage = i(:, startingColumns(k):endingColumns(k));
% se = strel('rectangle',[2 4]);
% dil = imdilate(subImage, se);
th = bwmorph(subImage,'thin',Inf);
n = imresize (th, [64 NaN], 'bilinear');
figure, imshow (n);
[L,num] = bwlabeln(n);
for z= 1 : num
bw= ismember(L, z);
% Construct filename for this particular image.
baseFileName = sprintf('char %d.png', y);
y=y+1;
% Prepend the folder to make the full file name.
fullFileName = fullfile(myFolder, baseFileName);
% Do the write to disk.
imwrite(bw, fullFileName);
% subplot(2,2,4);
% pause(2);
% imshow(bw);
end
% y=y+1;
end;
segm = (n);
Word image is as follow:
Why the code isn't work?
do you have any recommendation of another codes?
or suggested algorithm to make it works, to do a good segmentation on cursive character?
Thanks before.
Replace this code part from the posted code
% 0 where there is background, 1 where there are letters
letterLocations = verticalProjection > 0;
% Find Rising and falling edges
d = diff(letterLocations);
startingColumns = find(d>0);
endingColumns = find(d<0);
with the new code part
threshold=max(verticalProjection)/3;
thresholdedProjection=verticalProjection > threshold;
count=0;
startingColumnsIndex=0;
for i=1:length(thresholdedProjection)
if thresholdedProjection(i)
if(count>0)
startingColumnsIndex=startingColumnsIndex+1;
startingColumns(startingColumnsIndex)= i-floor(count/2);
count=0;
end
else
count=count+1;
end
end
endingColumns=[startingColumns(2:end)-1 i-floor(count/2)];
No changes needed for the rest of the code.
I want to plot the graph of the numerical solution of bisection method and show how it get close to the real solution .
my code:
% f=input('please enter the function:');
% xL=input('please enter the limits .from:');
% XR=input('to:');
% eps=input('please enter epsilon:');
f=#(x)x.^2-1;
XR=2;
xL=-2;
XL=xL ;
eps=0.001;
subplot(2,1,1);
title('graph 1');
ezplot(f);
hold on ;
% line([0 0],40);
% line(-40,[0 0]);
plot(XR,f(XR),'r*');
plot(xL,f(xL),'r*');
disp( 'the answers is : ');
for df=xL:0.15:XR
if f(xL)*f(df)<= 0
xR=df;
Roots = BisectionM(f,xR,xL,eps);
plot(Roots,f(Roots),'gs');
disp(Roots);
xL=df;
xR=XR;
end
end
subplot(2,1,2);
title('graph 2');
x0=fzero(f,xL);
sol = BisectionM(f,xR,xL,eps);
plot(1:1:100,ones(1,100)*x0);
hold on ;
plot(1:1:100,sol);
the function :
function[sol,Roots] = BisectionM(f,xR,xL,eps)
while abs(xR - xL) > eps
xM = (xR + xL) / 2;
if (f(xL))*(f(xM)) > 0
xL = xM;
sol=xM;
plot(xL,f(xL),'.');
else
xR = xM;
plot(xR,f(xR),'.');
sol=xM;
end
Roots = xM;
end
end
I don't know how to plot this so it will get closer to the solution (the blue line at the end). anyone?
I do not understand many things in your code, e.g. why BisectionM has two identical outputs under different variable names (sol, Roots), moreover only one output is used throughout the main function. Besides here is my guess what you might want:
The figure shows how the numerical solution converges with respect to iteration number. For this you have to store the iteration results in a vector (sol), please see below the modified code:
main.m
f=#(x)x.^2-1;
XR=2;
xL=-2;
XL=xL ;
eps=0.001;
subplot(2,1,1);
title('graph 1');
ezplot(f);
hold on ;
% line([0 0],40);
% line(-40,[0 0]);
plot(XR,f(XR),'r*');
plot(xL,f(xL),'r*');
disp( 'the answers is : ');
for df=xL:0.15:XR
if f(xL)*f(df)<= 0
xR=df;
Roots = BisectionM(f,xR,xL,eps);
plot(Roots(end),f(Roots(end)),'gs');
disp(Roots(end));
xL=df;
xR=XR;
end
end
subplot(2,1,2);
title('graph 2');
% give the wide interval again because it was changed previously
XR=2;
xL=-2;
x0=fzero(f,xL);
Roots = BisectionM(f,xR,xL,eps);
plot(1:length(Roots),ones(length(Roots),1)*x0, 'g');
hold on ;
plot(1:length(Roots),Roots,'Marker', '.');
xlabel('iteration number')
BisectionM.m
function Roots = BisectionM(f,xR,xL,eps)
% no preallocation because of while
ii = 1;
while abs(xR - xL) > eps
xM = (xR + xL) / 2;
if (f(xL))*(f(xM)) > 0
xL = xM;
sol=xM;
plot(xL,f(xL),'.');
else
xR = xM;
plot(xR,f(xR),'.');
sol=xM;
end
Roots(ii) = xM;
ii = ii + 1;
end
end
When I am accessing the structure fields like s(1).'fieldname' it's coming back empty. Only the last value can be seen, i.e s(97).'fieldname'. This is my code:
clc;
clear all;
data1= load('mydata.txt');
a=1;n=1;count=1;m=0;
while (count<98) % main loop starts
for i=a:a+1023
mydata1(i-m*1024)=data1(i); % taking 1k points in mydata1
end
m=m+1;
newdata=10*log10(abs(fft(mydata1))); % taking fft in newdata from mydata
for j=1:512
newdata1(2*j-1)=newdata(j); % interpolation of newdata to newdata1
newdata1(2*j)=newdata(j); % newdata1 size is 1024
end
a=j*n+513;
n=2*count+1;
% plot(newdata1);
% pause(1); % setting threshold
th=18;
newdata2(newdata1<th)=0; % newdata2 has 1024 0s and many 1s
newdata2(newdata1>=th)=1;
num=0;
for k=1:1023 % loop for reducing many 1s
if((newdata2(k)==1)&&(newdata2(k+1)==1))
num=num+1;
end
if(num>0 && (newdata2(k+1)==0 || k==1023))
for p = k-num:k
newdata2(p)=0;
end
p= (k-num)+floor(num/2);
newdata2(p)=1;
num=0;
end % loop ends
end
newdata2(1024)=0; % newdata2 with only 1s and 0s
binnum = find(newdata2);
x=length(binnum);
frequency=((100000/1024)*binnum);
for y=1:x
strength(y)=(newdata1(binnum(y)));
end
s= struct; % writing into a structure
s(count).frame=count;
s(count).freq=frequency;
s(count).str=strength;
count=count+1;
end
Where am I going wrong?
The line s= struct; %writing into a structure is creating a new structure variable each iteration of the while loop. Either move this line outside the loop, or omit it completely.