How to save a text file to a .mat file?
How do I save a '.txt' file as a '.mat' file, using either MATLAB or Python? I tried using textscan() (in MATLAB), and scipy.io.savemat() (in Python). Both didn't help.
My text file is of the format: value1,value2,value3,valu4 (each row) and has over 1000 rows.
Appreciate any help is appreciated. Thanks in advance.
2 answers

You can use
textscan
to read the file andsave
to save the variables into a .mat filefid = fopen('yourTextFile.txt'); C = textscan(fid,'%f %f %f %f'); fclose(fid); % maybe change the cells from `C` to a single matrix M = cell2mat(C); save('myMatFile.mat','M');
This works because your file seems to have a fixed format. Have a look at this and this

if what you need is to change file format:
mv example.mat example.txt
See also questions close to this topic

How to i open a file and remove certain characters based on args passed from command line
So i have a function which will essentially run and generate a report and save it with args.current_date filename. The issue i am having is to remove the extension .json from the filename being saved which really is not readable. Since i am passing dict as args , i cannot use the strip() method in order to do this. So far my function is follows :
parser = argparse.ArgumentParser() parser.add_argument("c", "currentdate", action="store", required=False) parser.add_argument("p", "previousdate", action="store", required=False) args = parser.parse_args() def custom_report(file_names, previous_data , current_data): reporting = open('reports/' + args.current_date+ "report.txt", "w") reporting.write("This is the comparison report between the directories" " " + args.current_date + " " "and" " " + args.previous_date + "\n\n") for item in file_names: reporting.write(item + compare(previous_data.get(item), current_data.get(item)) + "\n") reporting.close()
It has saved the file as '20190113.jsonreport.txt'. I want to be able to get rid of the '.json' aspect and leave it as '20190113report.txt'

Using scipy.fsolve on a matrix
Following the help I was given here I've been trying to implement it in my script but I'm failing at running it smartly.
I need to use this algorithm for each pixel of a 4072x3080 image, this takes around 1h30 for the whole process, so I tried to force it somehow but I'm getting this error:
ValueError Traceback (most recent call last) <ipythoninput1299c1f41dbba7> in <module>() > 1 res = scipy.optimize.fsolve(func, x0=np.ones((K.shape[0], K.shape[1])), args=(f[:,None], g[:,None], K)) /*/python2.7/sitepackages/scipy/optimize/minpack.pyc in fsolve(func, x0, args, fprime, full_output, col_deriv, xtol, maxfev, band, epsfcn, factor, diag) 146 'diag': diag} 147 > 148 res = _root_hybr(func, x0, args, jac=fprime, **options) 149 if full_output: 150 x = res['x'] /*/python2.7/sitepackages/scipy/optimize/minpack.pyc in _root_hybr(func, x0, args, jac, col_deriv, xtol, maxfev, band, eps, factor, diag, **unknown_options) 212 if not isinstance(args, tuple): 213 args = (args,) > 214 shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,)) 215 if epsfcn is None: 216 epsfcn = finfo(dtype).eps /*/python2.7/sitepackages/scipy/optimize/minpack.pyc in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape) 25 def _check_func(checker, argname, thefunc, x0, args, numinputs, 26 output_shape=None): > 27 res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) 28 if (output_shape is not None) and (shape(res) != output_shape): 29 if (output_shape[0] != 1): <ipythoninput7911c817cb57d> in func(x, f, g, K) 1 def func(x, f, g, K): > 2 return np.sum(f * np.exp(g*x), axis=0)  K 3 4 5 def derivative(x, f, g, K): ValueError: operands could not be broadcast together with shapes (13551616,) (4072,3328)
This is the code I've been trying:
def func(x, f, g, K): return np.sum(f * np.exp(g*x), axis=0)  K def derivative(x, f, g, K): return np.sum(g*f * np.exp(g*x), axis=0)
+
res = scipy.optimize.fsolve(func, x0=np.ones((K.shape[0], K.shape[1])), args=(f[:,None], g[:,None], K))
f
andg
are both(47,)
arrays, whereK
is a(4072, 3328)
imageElseway the slow process goes down this way: (but this one fails with derivative anyhow.
res = np.ones((mbn.shape[0],mbn.shape[1])) for i_x in range(0,mbn.shape[0]): if i_x%10 == 0: print i_x/4070 for i_y in range(0,mbn.shape[1]): res[i_x,i_y] = scipy.optimize.fsolve(func, x0=1, args=(f[:], g[:], K[i_x,i_y]) )
This would be the error if I try to use the slow method with the derivate
 ValueError Traceback (most recent call last) ValueError: object of too small depth for desired array  error Traceback (most recent call last) <ipythoninput83587dcccfd93> in <module>() 4 print i_x/4070 5 for i_y in range(0,mbn.shape[1]): > 6 res[i_x,i_y] = scipy.optimize.fsolve(func, fprime=derivative, x0=1, args=(f[:], g[:], K[i_x,i_y]) ) /*/python2.7/sitepackages/scipy/optimize/minpack.pyc in fsolve(func, x0, args, fprime, full_output, col_deriv, xtol, maxfev, band, epsfcn, factor, diag) 146 'diag': diag} 147 > 148 res = _root_hybr(func, x0, args, jac=fprime, **options) 149 if full_output: 150 x = res['x'] /*/python2.7/sitepackages/scipy/optimize/minpack.pyc in _root_hybr(func, x0, args, jac, col_deriv, xtol, maxfev, band, eps, factor, diag, **unknown_options) 232 with _MINPACK_LOCK: 233 retval = _minpack._hybrj(func, Dfun, x0, args, 1, > 234 col_deriv, xtol, maxfev, factor, diag) 235 236 x, status = retval[0], retval[1] error: Result from function call is not a proper array of floats.

Zapier gives error: `'unicode' object has no attribute 'copy'` for Python script
The script is simple:
import datetime today = datetime.date.today() next_thursday = today + datetime.timedelta(((3  today.weekday()) % 7)) while True: if 15 <= next_thursday.day <= 21: next_third_thursday = next_thursday break else: next_date = next_thursday + datetime.timedelta(days=1) next_thursday = next_date + datetime.timedelta(((3  next_date.weekday()) % 7)) import json return json.dumps(str(next_third_thursday))
How do I get this code to run? What's the issue here?

Making Rows ZeroMean in Matlab
The task is to make the rows of a matrix zero mean.
Given a 5x3 matrix A with numbers, I did the following:
 Created a 1x5 matrix row_mean keeping the mean of each row
row_mean = mean(A', 1)
 Used row_mean to zeromean each row of A
A = bsxfun(@minus, A, row_mean')
I'd like to know if there is a more direct way of doing it without having to transpose the matrices.

Converting window() function from MATLAB to python
I am trying to convert the following code line from MATLAB to python(3):
A=window(@tukeywin,XDimension,N_Param)
I have implemented it the following way:
import scipy.signal as window window.firwin(XDimension,window=('tukey',N_Param))
I am missing the
cutoff
argument. how do I take the same cutoff as the MATLAB code used? Is my implementation good or is this an easier method? 
Why doesn't 'discrete delay bloc' work with all discrete signals?
I try to make this equation in simulink:
ARRIVba(Ka) =((Ca  toba(Ka)).* ENTERba(Ka)/ Ca)+ (toba(Ka 1).* ENTERba(Ka 1)/ Ca);
By using a Matlab function bolck.
So I use a dicrete delay bloc to make
toba(Ka 1) and ENTERba(Ka 1).
But I don't have the same signal delayed, just for
toba(Ka 1), for ENTERba(Ka 1)
I have the same signal.
Can you help me please?

How to make a textfile based on its name
I have 4 text files. The name of these files include 2 digits (0 and 1). There are 2 numbers in each text file (1 row and two columns). Here are the files:
00.txt
10 20
01.txt
30 40
10.txt
50 60
11.txt
70 80
I am trying to write a python code that: 1 Creates a new text file 2 Opens the files one by one and copy the first and second columns of each file 3 Adds two more columns (Third and fourth columns corresponding to the first and second digit respectively in each file's name) into the new file based this rule:
If the digit is equal to 0, it should write 50 and if the digit is equal to 1, it should write 100. By the end of the day, I expect a text file like this:
10 20 50 50 30 40 50 100 50 60 100 50 70 80 100 100
Any idea how to do it in Python? Thanks in advance for your help.
I tried this solution:
import os #Get Data From File With File Name def GetDataFromFile(flename): with open(flename,'r') as f: flenamewithoutext=os.path.splitext(flename)[0] flecontent=list(f.read().split()) content=[i.replace("''", '') for i in flecontent] fledata=['100' if(int(d)==1) else '50' for d in flenamewithoutext ] content.extend(fledata) return content #Get All Files With Name .txt def GetFiles(): return [file for file in os.listdir() if file.endswith(".txt")] #Get All Available file in current directry textfiles=GetFiles() #This code will loop to each file and save data to result(apend every time) for t in textfiles: data=GetDataFromFile(t) result.append(data) #Your All Data into result list just print or add into file for r in result: print(' '.join(r))
However, there are 2 problems. First of all the "result" is not defined. The second one is something wrong in the "GetDataFromFile" function. Even if I delete the lines including "result" (The last lines of the code), it returns this error:
fledata=['100' if(int(d)==1) else '50' for d in flenamewithoutext ] ValueError: invalid literal for int() with base 10: '.'

Polish characters in C using files and lists
I need to get proper Polish characters "ąężźćśół". I used some solutions like
setlocale
,system chcp
,wchar_t
. Everything goes well as long as I don't use files/lists.wscanf
,wprintf
andwchar_t
works perfectly.But if I'm trying to read something from a file and save that into a list (even in array), then trying to put that to the screen, I can't get proper Polish characters, and in case of the lists, I'm getting different results from time to time for example, z` , A2 , like random characters from nowhere. I've been trying to get good results by using
fscanf
andfgets
with w(wide) variations, but it doesn't work. Did I something wrong?#include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <locale.h> struct dyk{ wchar_t line[200]; struct dyk *next; }; typedef struct dyk dyk; void printdyk(char name[100]){ dyk *wyp; wyp = malloc(sizeof(dyk)); wchar_t yt[100]; FILE *dyktando; dyktando = fopen(name, "r+"); if(dyktando == NULL){ wprintf(L"Błąd otwarcia pliku!\n"); //Can't open file }else{ fgets(&wyp>line, sizeof(dyk), dyktando); //reading from file and send to the list wprintf(L"%s\n", wyp>line); //write text from the list on the screen wchar_t yt[100]; wscanf(L"%s", &yt); //testing strings comparing, so I have to put some variables int n=strcmp(yt, wyp>line); //str compare printf("%d", n); //result, it gives me 1 every time } fclose(dyktando); }
I tested function with txt file that contents only one character "ż". Can't read from file properly. At the start of main function I put these 2 lines:
system("chcp 852"); setlocale(LC_ALL, ".852");
I'm using codeblock, mingw32gcc compiler, and no flags.

Why are my values being joined together when getting them from a class?
I am reading data from a text file and then storing each line in a class, each class is then being stored in an ArrayList.
For example after I have read each line from the text file I store the values in a class.
For Example:
while((line = reader.readLine()) != null){ line1 = line; line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); line5 = reader.readLine(); line6 = reader.readLine(); line7 = reader.readLine(); Person tempPerson = new Person(line1, line2, line3, line4, line5, line6, line7); person_list.add(tempPerson);
But when I get the values for line6:
Person tempPerson = person_list.get(0); out.print(tempPerson.getLine6());
The values that get outputted are merged with line7, for example, 'line7line6'.
All the other lines work perfectly fine apart from when I ask to get line 7 nothing gets returned.
Even when I have try to get details from another 'person' the same issue occurs in the same place.
I have tried new file readers and this hasnt helped, and also when checking on the debugger the values are being stored correctly in the class.
So instead of using an ArrayList I tried to store them in a Array and that didnt seem to help either.
I have been looking to see if there is an issue with my getters and setters and I can't seem to find a problem.

"Expecting miMATRIX type" error when reading MATLAB MATfile with SciPy
This is a MATLAB question: the problem is caused by interactions with MATLAB files and Python/numpy. I am tying to write a 3D array of type uint8 in MATLAB, and then read it in Python using numpy. This is the MATLAB code that creates the file:
voxels = zeros(30, 30, 30); .... fileID1 = fopen(fullFileNameOut,'w','s'); fwrite(fileID1, voxels, 'uint8'); fclose(fileID1);
This is the Python code that tries to read the file:
filename = 'File3DArray.mat' arr = scipy.io.loadmat(filename)['instance'].astype(np.uint8)
This is the error that I get when I run the python code:(I think this is the source of the problem. What is MM
raise TypeError('Expecting miMATRIX type here, got %d' % mdtype)
This is the output of the Linux command 'file' on the 3D array file that I created (I think this is the source of the problem. What is MMDF Mailbox?):
File3DArray.mat: MMDF mailbox
This is the output of the same Linux command 'file' on another 3D array file that was created by someone else in MATLAB:
GoodFile.mat: Matlab v5 matfile (little endian) version 0x0100
I want the files I create in MATLAB to be the same as GoodFile.mat (so that I can read them with the Python/Numpy code segment above). The output of the Linux 'file' command should be the same as the GoodFile output, I think. What is the MATLAB code that does that?

Loading multiple .mat files into a matrix and performing operations on it
I have 429 numerical matrices of identical size (107 rows by 36 columns), stored inside sequentially named
.mat
files (e.g:subj_00000.mat ... subj_00428.mat
). Here's what I need to do: Import into the MATLAB workspace.
 After importing, average all of them to generate another matrix, which will also have a dimension of 107x36.
 Finally, linearly correlate each column of the average matrix with each column of each of the original 429 matrices, to generate a new matrix of 429 rows and 36 columns.
So far I got to the stage of building a 107 x 36 x 429 array to be filled with my set of matrices.
S = dir(fullfile(D,'subj*.mat')); % D is the path where the .mat files are saved N = numel(S); C = cell(1,N); % preallocate cell array for k = 1:N S = load(fullfile(D,S(k).name)); C(k) = struct2cell(S); end A = cat(3,C{:}); % join all of the original matrices into a 107x36x429 array M = mean(A,3)
but I get the following error message:
Reference to nonexistent field 'name'. Error in myscript (line 6) S = load(fullfile(D,S(k).name));

.mat file to create a plot in Matlab
I have a main .mat file (
Results
) which include many sub .mat files. I want to use one of those sub .mat files (AblatedToparea
) to create a plot. I am using the following code but I am not getting the values but this:Data=load('Results.mat','AblatedToparea') Data = AblatedToparea: [4x1 double]