Matlab code to C# code conversion - c#

function [ samples,y, energies] = energy( speech, fs )
window_ms = 200;
threshold = 0.75;
window = window_ms*fs/1000;
speech = speech(1:(length(speech) - mod(length(speech),window)),1);
samples = reshape(speech,window,length(speech)/window);
energies = sqrt(sum(samples.*samples))';
vuv = energies > threshold;
y=vuv;
I have this matlab code and I need to write this code in c#. However I couldn't understand the last part of the code. Also i think speech corresponds to a data List or array according to first part of code. If it does not, please can someone explain what this code is doing. I just want to know logic. fs = 1600 or 3200;

The code takes an array representing a signal. It then breaks it into pieces according to a window of specified length, compute the energy in each segment, and finds out which segments have energy above a certain threshold.
Lets go over the code in more details:
speech = speech(1:(length(speech) - mod(length(speech),window)),1);
the above line is basically making sure that the input signal's length is a multiples of the window length. So say speech was an array of 11 values, and window length was 5, then the code would simply keep only the first 10 values (from 1 to 5*2) removing the last remaining one value.
The next line is:
samples = reshape(speech,window,length(speech)/window));
perhaps it is best explained with a quick example:
>> x = 1:20;
>> reshape(x,4,[])
ans =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
so it reshapes the array into a matrix of "k" rows (k being the window length), and as many columns as needed to complete the array. So the first "K" values would be the first segment, the next "k" values are the second segment, and so on..
Finally the next line is computing the signal energy in each segment (in a vectorized manner).
energies = sqrt(sum(samples.*samples))';

List<int> speech = new List<int>();
int window = 0;
int length = speech.Count();
int result = length % window;
int r = length - result;
// speech = speech(1: r, 1)

This:
(length(speech) - mod(length(speech),window)
is a formula
([length of speech] - [remainder of (speech / window)])
so try
(length(speech) - (length(speech) % window))
% is the symbol equivalent to mod(..)
EDIT I should say that I assume that is what mod(..) is in your code :)

Related

What's the proper way to generate 6 characters alphanumeric code in which sum of all characters equals 9? (Voucher code generator)

My first idea was to make an array/list that has values assigned to each character.
So for example:
array[0] =' 0'
array[10] = 'A'
[...]
Then code would pick a random number y between [0,x] for slot 1.
For next slot [0,(x-y)] etc. When y <= 0 then fill rest of the slots with '0'.
Would that be enough for a simple voucher code generator? (It's not my decision to make encryption with this rule)
I am worried that sum of 9 is quite low for 6 character code, letters won't be used at all since they all have value over 9.
To prevent situation like this:
540000, 630000, 180000
Should I make chance of '0' to appear more?
What do you guys think about it?
Maybe you could also suggest some other way of doing this.
#Edit
Examples:
112320 = 1+1+2+3+2+0 = 9 Valid code, sum equals 9
000900 = 0+0+0+9+0+0 = 9 Valid code, sum equals 9
003015 = 0+0+3+0+1+5 = 9 Valid code, sum equals 9
A0012B = 10+0+0+1+2+11 = 24 Invalid code
Let's say that the function Rand(n) creates a random integer number that can go from 0 up to n (n included), then you can do the following:
Sum = 0;
A[0] = Rand(9);
Sum += A[0];
A[1] = Rand(9 - Sum);
Sum += A[1];
A[2] = Rand(9 - Sum);
Sum += A[2];
...
I just wrote this down very quickly, I didn't check the boundaries, but such an algorithm should do the trick.

C# Code to print out prime numbers from 5 to N

Prime Number Generator Code
Do know that this question should be quite basic but i have spent hours trying to figure out why my code is stuck in the loop as below. Have added a Console.WriteLine($"{counttemp} , {count1} "); in the if loop to check the 2 numbers and seems like it is not breaking out of the if condition when the condition is true
this is the console output for the writeline in the if loop
5 , 5
6 , 2
7 , 7
8 , 2
9 , 3
10 , 2
11 , 11
12 , 2
13 , 13
14 , 2
15 , 3
16 , 2
17 , 17
18 , 2
19 , 19
Problematic Loop??
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
full code sequence
static void Main(string[] args)
{
int prime1 = 10000, count1, primetest1, counttemp;
for (counttemp = 5; counttemp <= prime1; counttemp++)
{
primetest1 = 1;
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
if (primetest1 == 1)
{
Console.Write($"{counttemp}");
}
}
}
You're almost there. The problem is that you're checking if your candidate number is a prime by getting the remainder when divided by each number up to and including the number itself.
I think you'll find that N is a factor of N for all values of N. To fix this, you should only be checking up to but excluding the number.
And, as an aside, you don't really need to check all the way up to N - 1. You only need to go to the square root of N, adjusted up to the nearest integer. That's because, if it has a factor above the square root, you would already have found a factor below it.
Consider 24 as an example. It has 6, 8, and 12 as factors above the square root, but the matching values below the square root are 4, 3, and 2 respectively.
And there's a another trick you can use by realising that if a number is a multiple of a non-prime, it's also a multiple of every prime factor of that non-prime. In other words, every multiple of 12 is also a multiple of 2 and 3.
So you only need to check prime numbers up to the square root, to see if there's a factor. And prime numbers, other than two or three, are guaranteed to be of the form 6x-1 or 6x+1, so it's quite easy to filter out a large chunk of candidates very quickly, by checking only for those values.
In other words, check two and three as special cases. Then start at 5 and alternately add 2 and 4: 5, 7, 11, 13, 17, 19, .... Not every number in that set is prime (e.g, 25) every prime is guaranteed to be in that set.
You can check out an earlier answer of mine for more detail on why this is so, and how to do this sequence efficiently.

How to merge to CSV file line by line

I'm having two CSV files where the first one looks like this:
ID Time PositionX PositionY
1 23
2 26
3 56
And another one that looks like this:
ID Time PositionX PositionY
25 2.5 5.5
28 4.1 5.6
35 4.8 6.2
66 5.5 7.5
The result that I want is:
ID Time PositionX PositionY
1 25(or 23) 2.5 5.5
2 28(or 26) 4.1 5.6
3 35(or 56) 4.8 6.2
So basically, I'm trying to merge two different files with different amount of data. But to combine them I need a key, the problem is that the key cannot be exactly the same for both of the data.
So I need to get Line by Line from one data set, see it's time, and see with the other dataset if there's a value close to this. If yes then merge them.
That's why I putted "25(or 23)" because the time is in milliseconds so I need to be sure that the line of the first dataset doesn't match with 28 but 25.
The final Key can be either 23 (from the first dataset) or 25 (from the second dataset). It doesn't matter as long as the line chosen is the closest to the value.
So I found out how to do it:
First I get the time of Dataset1:
String[] File1Rows = File.ReadAllLines(secondSensor.MyFile);
int number = Convert.ToInt32(File1Rows[1].Split(';')[0]);
Then create a list of strings made out of Dataset2:
String[] AccelerometerRows = File.ReadAllLines(fifthSensor.MyFile);
List<string> AccelerometterTimes = new List<string>(AccelerometerRows);
Then I take only the times in Dataset2 and put them into a list of strings
List<int> AccelerometterTimesList = new List<int>();
for (int i = 1; i < AccelerometterTimes.Count; i++)
{
var x = AccelerometerRows[i].Split(';')[0];
Console.WriteLine(x);
AccelerometterTimesList.Add(Convert.ToInt32(x));
}
Use a little bit of LinQ to get the closest value with O(n) complexity:
int closest = AccelerometterTimesList.Aggregate((x, y) => Math.Abs(x - number) < Math.Abs(y - number) ? x : y);
Then print it out:
Console.WriteLine("number: "+number);
Console.WriteLine("closest "+closest);
After this was found, now we use closest to get the line of Dataset2 that we need to get it's position. We take then the position, put them in the line of number from Dataset1.

Keep getting 0 as an output in C# division

I'm trying to divide a random number that is generated by 13. It can range from 1, 53. I need to divide the random number 13 to get a whole number (to determine what suit it is in a deck of cards). I need the suit to be out of 1-4.
Random number:
value = MyRandom.Next(1, 53);
Division:
suit = value / 13;
face = value % 13;
The suit keeps generating a 0 by the way.
I'm going to take a stab in the dark as to what you're really asking.
I'm guessing you're actually getting non-zero values for suit, but you're also occasionally getting zero. The main issue here, in this case, ultimately boils down to 0-based vs 1-based indexing.
What you need to do is do all the generating/computing with 0-based indexing, and then add 1 to shift to 1-based indexing. (Alternatively, you could use 0-based indexing)
Example code:
value = MyRandom.Next(0, 52); // notice the values are inclusively between 0 and 51
suit = (value / 13) + 1; // this will be between 1 and 4
face = (value % 13) + 1; // this will be between 1 and 13
To accomplish the task you are interested in, you should use a combination of casting your value to double and performing the Math.Ceiling operator.
Your Suit code should be written as:
var suit = Math.Ceiling((double)value / 13);
It would be helpful if you posted a little more code. Random is not an easy thing for a computer to do because so much architecture goes into not doing random calculations. Therefore, the random generator in .net is a pseudorandom number sequence based off of a seed value. You can come up with your seed however you wish, but I've often seen the ticks of the current DateTime used. Here is an example using your problem and I got the expected outcome that you are looking for:
var rand = new Random((int)(DateTime.Now.Ticks % int.MaxValue));
var value = rand.Next(1, 53);
var suit = value / 13;
var face = value % 13;
Hope this helps. Good luck!

Does a 2-char check digit for a barcode use the first or second char?

Based on my understanding of how check digits are supposed to be calculated for barcodes, namely:
0) Sum the values of all the characters at odd indexes (1, 3, etc.)
1) Multiply that sum by 3
2) Sum the values of all the characters at even indexes (o, 2, etc.)
3) Combine the two sums from steps 1 and 2
4) Calculate the check digit by subtracting the modulus 10 of the combined sum from 10
So for example, with a barcode "04900000634" the combined sum is 40*; To get the check sum, the modulus (40 % 10) == 0, and then 10 - 0 == 10.
Odd characters == 7; X3 = 21; Even characters == 19, for a combined sum of 40.
Since a check digit is a scalar value, what if the result of the check digit calculation is 10? Does one use "0" or "1"?
Here is the code I'm using (thanks to some help from here: Why does 1 + 0 + 0 + 0 + 3 == 244?); I'm assuming that the formula pseudocoded above applies regardless of the length (8 chars, 12 chars, etc.) and type (128, EAN8, EAN12, etc.) of the barcode.
private void button1_Click(object sender, EventArgs e)
{
string barcodeWithoutCzechSum = textBox1.Text.Trim();
string czechSum = GetBarcodeChecksum(barcodeWithoutCzechSum);
string barcodeWithCzechSum = string.Format("{0}{1}", barcodeWithoutCzechSum, czechSum);
label1.Text = barcodeWithCzechSum;
}
public static string GetBarcodeChecksum(string barcode)
{
int oddTotal = sumOddVals(barcode);
int oddTotalTripled = oddTotal*3;
int evenTotal = sumEvenVals(barcode);
int finalTotal = oddTotalTripled + evenTotal;
int czechSum = 10 - (finalTotal % 10);
return czechSum.ToString();
}
private static int sumEvenVals(string barcode)
{
int cumulativeVal = 0;
for (int i = 0; i < barcode.Length; i++)
{
if (i%2 == 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
private static int sumOddVals(string barcode)
{
int cumulativeVal = 0;
for (int i = 0; i < barcode.Length; i++)
{
if (i % 2 != 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
UPDATE
The calculator here: http://www.gs1us.org/resources/tools/check-digit-calculator claims that the check digit for 04900000634 is 6
How is that being arrived at?
UPDATE 2
This http://www.gs1.org/barcodes/support/check_digit_calculator
revises my understanding of the last part of the equation/formula, where it says, "Subtract the sum from nearest equal or higher multiple of ten = 60- 57 = 3 (Check Digit)"
So, in the case of 04900000634, the combined sum is 40. Based on that formula, the "nearest equal or higher multiple of ten" of 40 is 40, so 40-40=0, and I would expect that to be the check sum (not 6)...so, still confused...
UPDATE 3
I'm not understanding why yet, but mike z's comment must be correct, because when I reverse the "==" and "!=" logic in the sumOddVals() and sumEvenVals() functions, my results correspond to those generated by http://www.gs1us.org/resources/tools/check-digit-calculator
UPDATE 4
Apparently, based on http://en.wikipedia.org/wiki/European_Article_Number, the powers that be behind check digit calculations don't consider the first position to be position 0, but position 1. Confusing for developers, trained to see the first item as residing at index 0, not 1!
The check digit is always last.
Starting with the digit immediately to the left of the check digit and moving LEFT, sum each digit, applying a weight of 3 and 1 alternately.
The check digit is then the number which needs to be added to produce a result that is a multiple of 10.
This works for ALL EAN/UPC codes - UPC-E, EAN-8 (which is all valid 8-digit codes except those whoch start 0,6 or 7) UPC-A (12-digit), EAN-13, EAN-14 (sometimes call "TUN" or "Carton" codes) and SSCCs (actually 18-digit, but implemented as part of the EAN128 standard with an AI of '00', misleading some into believing they're 20-digit codes)
When UPC-E was introduced, the original scheme was [language][company][product][check]. 0,6 and 7 were assigned to English and the remainder unassigned. [company] and [product] were variable-length with total 6 digits; short company numbers for companies with many products, long for companies with few products.
EAN used the remainder of the numbers, but assigned [country][company][product][check] where country was 2-digit.
That system soon ran out of puff, but is still occasionally assigned for very small products - and the original products that had numbers before UPC-A/EAN-13 was introduced.
UPC-A used the same schema as UPC-E, but lost the reference to 'language'. 0,6 and 7 were assigned to US/Canada. The company+product was extended to 10 digits.
EAN-13 extended the scheme to 13 digits, 2 for country, 10 for company+product, 1 to check. UPC-A was compatible by prefixing a leading "0".
By implementing the 13-digit scheme, US companies could track each of these codes and UPC-As did not need to be issued on products that already had an EAN-13 assigned. This was scheduled for completion about 8 years ago, but some companies still lag behind.
EAN-14s are used for carton outers. The leading digit is normall referred to as a "Trade Unit Identifier/Number" Hence the entire code is sometimes called a TUN. At first, there was an attempt to codify the leading digit (1=1doz, 2=2doz, etc.) but this was soon abandoned. Most companies use the number as a packaging level (1=cluster of individual items, 2=tray of clusters, 3=box of trays - depending on each company's preference. 9 is reserved. Not a good idea to use 0 (though some companies have) since it produces the same check-digit as the 13-digit code. I've used this for EAN128 codes bearing the batch number on non-retail goods; AI=01;EAN-14 (=EAN13 with TUN=0);AI=10;batch-number.
SSCCs are another can of worms. They're 18-digit - the first digit was originally used as a logistical descriptor, then there's the country-code, manufacturer-code and package-number with a check-digit. Originally, "3" meant an "external" pallet and "4" an "Internal" pallet, but this fell into disuse as impractical as an "Internal" pallet then has to be re-numbered if it gets sent "outside" and vice-versa.
And of course 2-digit country-codes have been supplanted by 3-digit as more countries have adopted the system.
There are different weights for different barcode formats. You have described the format for the EAN format - a 1313 weighting. Whereas UPC uses a 3131 weighting scheme. ISBN-10 uses a completely different scheme - the weights are different and the calculation is done modulo 11.
I think the reference you are using is assuming that the digits are indexed starting at 1 not 0. The effect is that you have mixed up odd and even characters. So the sum is 3 x 19 + 7 = 64 and therefore the check digit is 6 not 0. For EAN and UPC, the check digit is the value that must be added to the sum to get a number evenly divisible by 10.
Update
Your description of the check digit algorithm is accurate only for certain classes of EAN barcodes because the weights are aligned such that the last digit is always weighted by 3 (see EAN Number). Therefore, depending on the exact EAN scheme (8,12,13 or 14 digit) odd or even digits are weighted differently.
Thus the proper weights are
0 4 9 0 0 0 0 0 6 3 4
3 1 3 1 3 1 3 1 3 1 3
Giving a sum of 64 and a check digit of 6.
Based on this: http://www.gs1.org/barcodes/support/check_digit_calculator, barcode calculation formulas can either start with 1, or start with 3, based on whether the ultimate length of the barcode is even (including the checksum val) or add. If the total number of chars, including the checksum, is even, the 1st digit has a weight of three; otherwise (total char count is odd), the 1st digit has a weight of 1. In either case, 3s and 1s alternate, as "13131313..." or "31313131..."
But they always seem to end with a weight of 3; so, it shouldn't matter how long the barcode is, or whether it is odd or even. Simply calculate the value "backwards," assuming the last digit has a weight of 3; HOWEVER, whether the barcode is of even or odd length, that is to say, whether the last digit and those that alternate with it are even or odd makes all the difference in the world, so that has to be noted, too. The "inside" ordinals begin with the penultimate character in the barcode, and skip one backwards; the "outside" ordinals are the last one and then every other one. Anyway, here is the code which, AFAIK, should work to generate and validate/verify check digits for all barcode types:
private void button1_Click(object sender, EventArgs e)
{
string barcodeWithoutCheckSum = textBox1.Text.Trim();
string checkSum = GetBarcodeChecksum(barcodeWithoutCheckSum);
string barcodeWithCheckSum = string.Format("{0}{1}", barcodeWithoutCheckSum, checkSum);
label1.Text = barcodeWithCheckSum;
textBox1.Focus();
}
public static string GetBarcodeChecksum(string barcode)
{
int oddTotal;
int oddTotalTripled;
int evenTotal;
// Which positions are odd or even depend on the length of the barcode,
// or more specifically, whether its length is odd or even, so:
if (isStringOfEvenLen(barcode))
{
oddTotal = sumInsideOrdinals(barcode);
oddTotalTripled = oddTotal * 3;
evenTotal = sumOutsideOrdinals(barcode);
}
else
{
oddTotal = sumOutsideOrdinals(barcode);
oddTotalTripled = oddTotal * 3;
evenTotal = sumInsideOrdinals(barcode);
}
int finalTotal = oddTotalTripled + evenTotal;
int modVal = finalTotal%10;
int checkSum = 10 - modVal;
if (checkSum == 10)
{
return "0";
}
return checkSum.ToString();
}
private static bool isStringOfEvenLen(string barcode)
{
return (barcode.Length % 2 == 0);
}
// "EvenOrdinals" instead of "EvenVals" because values at index 0,2,4,etc. are seen by the
// checkdigitmeisters as First, Third, Fifth, ... (etc.), not Zeroeth, Second, Fourth
private static int sumInsideOrdinals(string barcode)
{
int cumulativeVal = 0;
for (int i = barcode.Length-1; i > -1; i--)
{
if (i % 2 != 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
// "OddOrdinals" instead of "OddVals" because values at index 1,3,5,etc. are seen by the
// checkdigitmeisters as Second, Fourth, Sixth, ..., not First, Third, Fifth, ...
private static int sumOutsideOrdinals(string barcode)
{
int cumulativeVal = 0;
for (int i = barcode.Length - 1; i > -1; i--)
{
if (i % 2 == 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
UPDATE
With the above code, it is easy enough to add a function to verify that a barcode (with appended checkdigit) is valid:
private static bool isValidBarcodeWithCheckDigit(string barcodeWithCheckDigit)
{
string barcodeSansCheckDigit = barcodeWithCheckDigit.Substring(0, barcodeWithCheckDigit.Length - 1);
string checkDigit = barcodeWithCheckDigit.Substring(barcodeWithCheckDigit.Length - 1, 1);
return GetBarcodeChecksum(barcodeSansCheckDigit) == checkDigit;
}

Categories