how to convert mat file into xlsx file - excel

After executing code, I received an error:
load('firstdiff.mat')
xlswrite('test.xlsx', firstdiff)
mat file consist only numeric values (0 and 1)
Undefined function or variable 'firstdiff'

Using load without output arguments is something which often confuses programmers. I recommend to use it with an output argument:
data=load('firstdiff.mat')
This way you get a struct containing the data of your mat file. A typical next step would be using fieldnames(data) to check which variables are present or if you already know, index a variable with an expression like data.x
In this case I assume you only have one variable in your matfile.
data=load('firstdiff.mat');
fn=fieldnames(data); %get all variable names
assert(numel(fn)==1); %assert there is only one variable in your mat, otherwise raise error
firstdiff=data.(fn{1}); %get the first variable
xlswrite('test.xlsx', firstdiff); %write it

Related

Reading a list of tuples from a text file in python

I am reading a text file and I want to read a list of tuples so that I can add another tuple to it in my program and write that appended tuple back to the text file.
Example in the file
[('john', 'abc')]
Want to write back to the file as
[('john', 'abc'), ('jack', 'def')]
However, I whenever I keep writing back to the file, the appended tuple seems to add in double quotes along with square brackets. I just want it to appear as above.
You can write a reusable function which takes 2 parameters file_path (on which you want to write tuple), tup (which you want to append) and put your logic inside that. Later you can supply proper data to this function and it will do the job for you.
Note: Don't forget to read the documentation as comments in code
tuples.txt (Before writing)
[('john', 'abc')]
Code
def add_tuple_to_file(file_path, tup):
with open(file_path, 'r+') as f:
content = f.read().strip() # read content from file and remove whitespaces around
tuples = eval(content) # convert string format tuple to original tuple object (not possible using json.loads())
tuples.append(tup) # append new tuple `tup` to the old list
f.seek(0) # After reading file, file pointer reaches to end of file so place it again at beginning
f.truncate() # truncate file (erase old content)
f.write(str(tuples)) # write back the updated list
# Try
add_tuple_to_file("./tuples.txt", ('jack', 'def'))
tuples.txt (After writing back)
[('john', 'abc'), ('jack', 'def')]
References
https://www.geeksforgeeks.org/python-ways-to-convert-string-to-json-object/
How to open a file for both reading and writing?
You can use ast.literal_eval to get the list object from the string.
import ast
s = "[('john', 'abc')]"
o = ast.literal_eval(s)
print(repr(o)==s)
o.append(('jack', 'def'))
newstr = repr(o)
print(newstr)
Here it is in action.

I try to sum all numbers in a txt file, putting two workable variables in one line and it returns 0. What's gone wrong?

I used 3 lines of codes which worked well. Then I try to contract them into one line, which I believe can be done by putting two variables together. But for some reason, the contracted codes only returned 0 instead of the actual sum that can be computed before. What's gone wrong in the contracted codes?
hand = open('xxxxxx.txt')
# This is a text file that contains many numbers in random positions
import re
num = re.findall('[0-9]+', hand.read())
# I used regular expression on variable 'num' to extract all numbers from the file and put them into a list
numi = [int(i) for i in num]
# I used variable 'numi' to convert all numbers in string form to integer form
print(sum(numi))
# Successfully printed out the sum of all integers
print(sum([int(i) for i in re.findall('[0-9]+', hand.read())]))
# Here is the problem. I attempted to contract variables 'num' and 'numi' into one line of codes. But I only got 0 instead of the actual sum from it`enter code here`
if you execute all the code like I see up there, it is normal to get 0 because you didn't re-open the file after using it the first time, just re-open the file "hand" or leave the final line that you want to use and delete the three lines before it.
This code works fine for me -
hand = open('xxxxx.txt')
import re
print(sum([int(i) for i in re.findall('[0-9]+', hand.read())]))
You have to close the file and reopen it before running the last line.

Simple Moving Average on a .cat file with Python 3.6

I'm trying to write a program that performs a moving average on a .cat file with ~500 float values, then saves the result to another file. The code works fine if I give in input an array like x=[1,2,3...] but when I try with the file I get the error message:
TypeError: unsupported operand type(s) for *: 'float' and '_io.TextIOWrapper'
May someone please help me?
import numpy as np
def movingaverage (values, window):
weights = np.repeat(1.0,window)/window
sma = np.convolve(values,weights,'valid')
return sma
with open('Relative_flux.cat','r') as f:
data=movingaverage(f,3)
print(data)
f is a file handle, not the contents of the files. The contents must first be read, then formatted into an array of floats, before being handed to your function, which expects an array of floats.
Assuming the file is formatted in the way you mention in your comment:
data=movingaverage([float(x) for x in f.read().split()], 3)
read() reads the whole content of the file and returns it as a string.
split() splits the string at all whitespaces
[float(x) for x in [...]) applies the conversion to float to every string, returning an array of floats.
This code will throw an exception if any of the entries in the file cannot be converted to float, or if the format is not consistently floating point numbers separated by whitespaces.
Your object f is an open file rather than an array of floating point values. You need to read lines from the file and load the floating point values into an array, which depends on the specific file format you're using.

How to do file operation in verilog?

$fmonitorh(file_handler, conv1, conv2, conv3, conv4);
In this conv1, conv2... are my outputs and I want to write these values in text file, line by line or , between two values. While running above command I am getting values in one line only.
the format of the file output command is:
$f...(file_handler, format_string, arg1, ...);
the format_string is the one which defines output layout and uses '%' specifiers to layout your data, similar to printf in 'c'.
so, you can use something like this:
$fmonitorh(file_handler, "%x\n%x\n%x\n%x", conv1, conv2, conv3, conv4);

dynamically creating key and values in dictionary in Python

I am new to Python. I am here reading several lines in a file having a format
121212-pr-ba-su_re;m1;1;10000
I have extracted (pr-ba-su) content using split function. Please see the code which i wrote. I wish to store the Prefix-base-suffix as a key and its value as ID (which is extracted in the first line of loop) in a dictionary. (I want to replace the key with value in another list. Therefore, i am trying to create a dictionary.)
data ={}
f = open('var_test.txt')
for line in f:
part,m,t,ID = line.split(';',3)
partnumb,r = part.split('_',1)
item,prefix,base,suffix =partnumb.split('-',3)
data[prefix'-'base'-'suffix] =ID
But i am getting an error as Syntax Error
data(getattr([prefix'-'base'-'suffix])) =PID
^SyntaxError: invalid syntax
I have tried using getattr()function,and update function but no avail.Can anybody help me? Thanks a lot.
The line data[prefix'-'base'-'suffix] =ID is your problem. It is not valid Python syntax.
You could get the results you expect by substituting for this line
data["{}-{}-{}".format(prefix, base, suffix)] = ID

Resources