I have an audio signal of length 12769. I'm trying to perform STFT on it by breaking it into small windows of 1024 samples. This gives me with 12 exact windows while there are 481 points remaining. Since i need 543 (1024 - 481) more points to make up 1024 samples, i used the following code to zero pad.
f = [a zeros(1,542)];
where a is the audio file.
However i get an error saying
??? Error using ==> horzcat
CAT arguments dimensions are not consistent.
How can I overcome this?
Your vector a is a column vector and cannot be concatenated with row vector zeros(1,542). Use zeros(542,1) instead.
However, it is much easier to just use
f = a;
f(1024*ceil(end/1024)) = 0;
MATLAB will zero pad the vector up to element 1024, and it is independent of the array being column or row.
You can either remove the excess 481 samples using
Total_Samples = length(a);
for i=1 : Total_Samples-481
a_new[i] = a[i];
or you could add an additional 543 Zero samples by using
Total_Samples = length(a);
for i=Total_Samples+1 : Total_Samples+543
a[i] = 0 ;
Related
I have a for loop that shifts a signal over a certain amount and appends it to an array. How can I vectorize the circshift section so I don't need to use the for loop?
fs_rate=10
len_of_sig=1; %length of signal in seconds
t=linspace(0,len_of_sig,fs_rate*len_of_sig);
y=.5*sin(2*pi*1*t);
for aa=1:length(y)
y_new(aa,:)=circshift(y,[1,aa+3]); %shifts signal and appends to array
end
plot(t,y_new)
PS: I'm using Octave 4.2.2 Ubuntu 18.04 64bit
You can use the gallery to create a circular matrix after using circshift for your base shift:
base_shift = 4;
fs_rate = 10;
len_of_sig = 1; # length of signal in seconds
t = linspace (0, len_of_sig, fs_rate*len_of_sig);
y = .5 * sin (2*pi*1*t);
y = gallery ("circul", circshift (y, [1 base_shift]));
Or if you want to know how it was implemented, take a look at its source code type gallery
I'm writing a code to solve Ax=b using MATLAB's x=A\B. I believe my problem lies within getting the data from the files into the array. Right now, the solution vector is coming out to be a load of 0's
The matrices I'm using have 10 rows respectively. They are aligned correctly in the text files.
% solve a linear system Ax = b by reading A and b from input file
% and then writing x on output file.
clear;
clc;
input_filename = 'my_input.txt';
output_filename = 'my_output.txt';
% read data from file
fileID = fopen('a_matrix.txt', 'r');
formatSpec = '%d %f';
sizeA = [10 Inf];
A = load('b_matrix.txt');
A = A'
file2ID = fopen('b_matrix.txt','r');
formatSpec2 = '%d %f';
sizeB = [10 Inf];
b = load('b_matrix.txt');
fclose(file2ID);
b = b'
% solve the linear system
x = A\b;
% write output data on file
dlmwrite('my_output.txt',x,'delimiter',',','precision',4);
% print screen
fprintf('Solution vector is: \n');
fprintf('%4.2f \n', x);
I answered my own question but I felt the need to share in case anyone else has similar troubles.
% solve a linear system Ax = b by reading A and b from input file
% and then writing x on output file.
clear;
clc;
input_filename = 'my_input.txt';
output_filename = 'my_output.txt';
% read data from file
f = textread('a_matrix.txt', '%f');
vals = reshape(f, 11, []).';
A = vals(:,1:10);
b = vals(:,11);
% solve the linear system
x = A\b;
% write output data on file
dlmwrite('my_output.txt',x,'delimiter',',','precision',4);
% print screen
fprintf('Solution vector is: \n');
fprintf('%4.2f \n', x);
I ended up combining the 'a' and 'b' matrix into a single text file for simplicity. Now, MATLAB reads data in by columns, so it is necessary to use 'reshape' in order to fit the data within the array correctly. Then, I filtered out the information from the single matrix by columns, using the 'vals' function as seen in my code. The 'A' matrix is essentially all numbers in columns 1 through 10, while the 'B' matrix is the 11th (and final) column.
Using MATLAB's x=A\b function, I was able to solve the linear system of equations.
I am in the process of writing an api that will convert the native SEXP objects to protocol buffers so that I can serialize them. My problem arises when trying to convert a SEXP object from a dataframe using recursive function. The issue is when I find an INTSXP that inherits factor; the factor only sees two levels in the level count. Is there an example somewhere about how to handle a factor in c? Or does someone have advice atleast on why I am only seeing two levels. Also I have a feeling I am going to run into another issue when handling the NA but haven't tried handling that yet.
I am guessing the issue is some internal feature of R is seeing red twice and just creating a pointer when creating the dataframe.
R Version
R version 3.0.2 (2013-09-25)
CODE
Here is the R code that I am executing. It is running through a jni interface and getting back a protocol buffer.
String command = "d <- c(1,2,3,4); e <- c(\"red\", \"white\", \"red\", NA); f <- c(TRUE,TRUE,TRUE,FALSE); mydata <- data.frame(d,e,f);";
Here is where I am handling the types.
case INTSXP: // #define INTSXP 13 /* integer vectors */
// factors have internal type INTSXP too
if (Rf_inherits(model, "factor")) {
int levelCount = Rf_nlevels(model);
if (levelCount > 0) {
fprintf(stderr, "Got a factor with count %d\n", levelCount);
SEXP levels = Rf_getAttrib(model, Rf_install("levels"));
fill_rexp(rexp, levels);
}
break;
}
rexp->rclass = REXP__RCLASS__INTSXP;
rexp->n_intvalue = LENGTH(model);
rexp->intvalue = malloc(sizeof(rexp->intvalue) * (rexp->n_intvalue));
for (i = 0; i < rexp->n_intvalue; i++) {
fprintf(stderr, "Setting value of rexp to %d %d\n",i, (INTEGER(model)[i]));
rexp->intvalue[0] = (INTEGER(model)[i]);
}
break;
case REALSXP: //#define REALSXP 14 /* real variables */
rexp->rclass = REXP__RCLASS__REALSXP;
Notice in the output that the "Got a factor with count 2" is that I thought would be 4. Is there a cleaner way to handle this in c?
Type of model is 19
Size of vector is 3
Type of model is 14
Setting value of rexp to 0 1.000000
Setting value of rexp to 1 2.000000
Setting value of rexp to 2 3.000000
Setting value of rexp to 3 4.000000
Type of model is 13
Got a factor with count 2
Type of model is 16
Number of strings 2
Type of model is 10
Count of children in vector 3
If you're converting a factor to character, you want Rf_asCharacterFactor.
I found a solution that works!! I found the example in the Rcpp. I tried the Rf_coerce to see if that was working in R-3.0.2 but when I tried to coerce it to STRSXP it returned me integers. So I used the example code below to get this to return me the values from the factor.
case INTSXP:
{
// return Rf_coerceVector( x, STRSXP );
// coerceVector does not work for some reason
SEXP call = PROTECT( Rf_lang2( Rf_install( "as.character" ), x ) ) ;
SEXP res = PROTECT( Rf_eval( call, R_GlobalEnv ) ) ;
UNPROTECT(2);
BTW in the future I would have just spent some time learning cpp better and used Rcpp but my experience with cpp is lacking.
I have the task of encoding and decoding some bytes of sound using parity checksum method and Reed-Solomon Erasure Correction.
I've done my encoding for first method(parity checksum) but need help completing the second method which is detection by Reed-Solomon Erasure Correction.
So far I know that, RS code adds t symbols to k symbols of data. So it is able to locate and correct up to t/2 symbols or if the error locations are known so called erasures. It can correct up to t. For this task I have to use Galois field GF(28) to represent each symbol as a byte. Operation addition and subtraction are based on XOR. So over all I have to employ Reed-Solomon codes that are capable of correction up to t=3 erasures. The computation of a single Reed Solomon code in now as follow
C0 | C1 |........| Ck-1 | Ck | Ck+1 | Ck+2
so the code bytes can be viewed as vector c=[c0,c1,...,ck+2]
and a single code C is computed from k bytes of data as follow
d=[d0,d1,...,dk-1], so my encoding and decoding process require the following Vandermonde matrix F
1 1 12 13 ... 1k-1
1 2 22 23 ... 2k-1
...
1 k+2 (k+2)2 (k+2)3 ... (k+2)k-1
1 k+3 (k+3)2 (k+3)3 ... (k+3)k-1
so a simple matrix vector multiplication using F & D we get C=F.D.
so far what I did for encoding is as follow :
#else
void fox_encode(Buffer* bufin, Buffer* bufout, FoxEncData* algorithm_data){
// Your encoder for Task 2.C.3 goes in here !!!
while (bufin->size >= 1){
guint8 databyte = bufin->data[0]; //Pick up a byte from input buffer
buffer_push_byte (bufout, databyte); //Send it 3 times
buffer_push_byte (bufout, databyte);
buffer_push_byte (bufout, databyte);
buffer_pop (bufin, 1); //Remove it from the input buffer
}
}
#endif
I need code to complete this code for encoding and decoding my fox_encode and fox_decode class using Reed-Solomon Erasure Correction. Any Help will be appreciated to complete this task as soon as possible.
Thanks in advance
You can take look at my RS(255,255-k) C-implementation which is available from my homepage.
It handles both errors and erasures and corrects any byte error/erasure patterns bounded by:
(2*errorCount + erasureCount) <= k.
There is now a good tutorial on Wikiversity which details how to handle both erasures and errors.
Here is an outline of what you need to implement for the erasures decoding process:
Compute the syndromes. Then check if it's all 0 coefficients, the message does not need correction, else continue.
Call the Forney algorithm with the syndrome and the erasures positions as input to compute the erasure magnitude polynomial (ie, the values to subtract from message polynomial to get the original message back).
Subtract message - erasure_magnitude_polynomial to recover your original message (if within Singleton bound).
Apart from the Forney algorithm which can be a bit involving, all the other parts are very simple and straightforward. Indeed, the most difficult parts such as Berlekamp-Massey algorithm and Chien search are only necessary when you want to decode errors, and Forney syndromes computation is only necessary if you want to correct both erasures and errors (ie, errata) -- although I have read some paper which describe that Forney syndromes computation can be bypassed, but I never seen such a code.
I've got some code, and I've been trying to make some minor tweaks to it. It used to use fgets to load in a single character from a line, and use it to colour points in a 3D plot. So it would read
a
p
p
n
c
and then use other data files to assign what x, y, z points to give these. The result is a really pretty 3D plot.
I've edited the input file so it reads
0
1
1
0
2
2
0
and I want it to colour numbers the same colour.
This is where I've gotten so far with the code:
function PlotCluster(mcStep)
clear all
filename = input('Please enter filename: ', 's');
disp('Loading hopping site coordinates ...')
load x.dat
load y.dat
load z.dat
temp = z;
z = x;
x = temp;
n_sites = length(x);
disp('Loading hopping site types ...')
fp = fopen([filename]);
data = load(filename); %# Load the data
% Plot the devices
% ----------------
disp('Plotting the sample surface ...')
figure
disp('Hello world!')
ia = data == 0;
in = data == 1;
ip = data == 2;
disp('Hello Again')
plot3(x(ia),y(ia),z(ia),'b.') %,'MarkerSize',4)
hold on
plot3(x(ic),y(ic),z(ic),'b.') %,'MarkerSize',4)
plot3(x(in),y(in),z(in),'g.') %,'MarkerSize',4)
plot3(x(ip),y(ip),z(ip),'r.') %,'MarkerSize',4)
daspect([1 1 1])
set(gca,'Projection','Perspective')
set(gca,'FontSize',16)
axis tight
xlabel('z (nm)','FontSize',18)
ylabel('y (nm)','FontSize',18)
zlabel('x (nm)','FontSize',18)
%title(['Metropolis Monte Carlo step ' num2str(mcStep)])
view([126.5 23])
My issue is I'm getting this error
Index exceeds matrix dimensions.
Error in PlotCluster (line 34)
plot3(x(ia),y(ia),z(ia),'b.') %,'MarkerSize',4)
And I don't see why ia would go out of bounds of the x array. Is it to do with changing the fgets to a load statement? It was the only way to get it read the correct numbers in (not 49s and 50s which was very odd.)
The main bits that are sticking me are these lines (where the number used to correspond to 'a','n','p' etc)
ia = data == 0;
in = data == 1;
ip = data == 2;
They look like implied if statements with assignment from data to ia etc. where ia becomes an array. But I'm not sure.
Any help understanding this would be greatly appreciated.
I've fixed the issue, I hadn't updated my input correctly. To clear this up for anyone who comes to this question: ia = data ==0 means 'Make an array the same size as data, and fill it with 1 or 0 depending on if the logic (data == 0) is true or false'