Non-cell array with uigetfile in Matlab - arrays

My code has 2 parts. First part is an automatic file opening programmed like this :
fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
delimiterIn = ' ';
headerlinesIn = 11;
for d = 1:numberOfFiles
filenames(d) = cellstr(files(d).name);
end
for i=1:numberOfFiles
data = importdata(fullfile(fichierref,filenames{i}),delimiterIn,headerlinesIn);
end
Later on, I want the user to select his files for analysis. There's a problem with this though. I typed the lines as follow :
reference = warndlg('Choose the files from which you want to know the magnetic field');
uiwait(reference);
filenames = uigetfile('./*.txt','MultiSelect', 'on');
numberOfFiles = numel(filenames);
delimiterIn = ' ';
headerlinesIn = 11;
It's giving me the following error, after I press OK on the prompt:
Cell contents reference from a non-cell array object.
Error in FreqVSChampB_no_spec (line 149)
data=importdata(filenames{1},delimiterIn,headerlinesIn);
I didn't get the chance to select any text document. Anyone has an idea why it's doing that?

uigetfile is a bit of an annoying when used with `MultiSelect': when you select multiple files the output is returned as a cell array (of strings). However, when only one file is selected the output is of type string (not a cell array with a single cell, as one would have expected).
So, in order to fix this:
filenames = uigetfile('./*.txt','MultiSelect', 'on');
if ~iscell(filenames) && ischar( a )
filenames = {filenames}; % force it to be a cell array of strings
end
% continue your code here treating filenames as cell array of strings.
EDIT:
As pointed out by #Sam one MUST verify that the user did not press 'cancel' on the UI (by checking that filenames is a string).

Related

Accessing an element by index in a nested array returns undefined

I am currently working on copying data from one row to another with spaces between for data that needs to be entered manually. I am trying to copy most of the data in the currently selected row and paste it to a blank row without appending any new rows. The issue I'm currently having is when I try to directly access the values in a nested array. The array will log correctly when called but the values in the array will not show individually unless I am using the getValue function but that only shows the first item of the array.
This is what the code looks like now:
const sheet = SpreadsheetApp.getActiveSheet();
const activeCell = sheet.getCurrentCell();
function test() {
let activeRow = sheet.getRangeList([activeCell.getA1Notation() + ':' + activeCell.offset(0,1).getA1Notation(), activeCell.offset(0,3).getA1Notation(), activeCell.offset(0,5).getA1Notation() + ':' + activeCell.offset(0,7).getA1Notation()]).getRanges();
Logger.log(activeRow[0][0].getValue())
};
This is giving me the error 'TypeError: Cannot read property 'getValue' of undefined. However when I only use one index in the Logger such as:
Logger.log(activeRow[0].getValue())
it gives me the first value in the indexed array.
If I change the function to getValues as well as only using one index such as:
Logger.log(activeRow[0].getValues())
it returns an array of the values of the first two cells in the row.
I understand the double-indexing is what's causing the issue I'm just not sure why it's causing an issue but I would like to be able to access the data individually so I can then copy the data to the new row.
I am also open to further optimization or a different way of accomplishing this that I may have missed.
Try it this way:
function test() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const cell = sh.getActiveCell();
const r = sh.getRange(cell.getRow(),1,1,sh.getLastColumn()).getValues()
Logger.log(r[0][0])
}
Execution log
1:46:41 PM Notice Execution started
1:46:42 PM Info 10.0
1:46:43 PM Notice Execution completed
A
B
C
D
E
F
G
11
10
11
12
13
14
15
16

How to create a loop to extract data from a .csv file

I face this issue and can't seem to find a fix except with Scipy or Numpy, both of which I don't wanna use in this case.
From a .csv file, I want to extract the values of the first column :
enter image description here
Which I manage to do with the following code :
mat_data = open('file.csv')
data_reader = csv.reader(mat_data)
list_data = list(data_reader)
value1=float(list_data[1][0])
value2=float(list_data[2][0])
value3=float(list_data[3][0])
I'd now like to create a loop that could be used and create value"i" no matter how many lines long my .csv is.
Any idea?
This did the trick for me !
mat_data = open('file.csv')
data_reader = csv.reader(mat_data)
list_data = list(data_reader)
i=0
value=dict()
for i in range(1,len(list_data)):
value[i]=list_data[i][0]
print value[i]

get_by_id() not returning values

I am writing an application that shows the user a number of elements, where he has to select a few of them to process. When he does so, the application queries the DB for the rest of the data on these elements, and stacks them with their full data on the next page.
I made an HTML form loop with a checkbox next to each element, and then in Python I check for this checkbox's value to get the data.
Even when I'm just trying to query the data, ndb doesn't return anything.
pitemkeys are the ids for the elements to be queried. inpochecks is the checkbox variable.
preqitems is the dict to save the items after getting the data.
The next page queries nothing and is blank.
The comments are my original intended code, which produced lots of errors because of not querying anything.
request_code = self.request.get_all('rcode')
pitemkeys = self.request.get_all('pitemkey')
inpochecks = self.request.get_all('inpo')
preqitems = {}
#idx = 0
#for ix, pitemkey in enumerate(pitemkeys):
# if inpochecks[ix] == 'on':
# preqitems[idx] = Preqitems.get_by_id(pitemkey)
# preqitems[idx].rcode = request_code[ix]
# idx += 1
for ix, pitemkey in enumerate(pitemkeys):
preqitems[ix] = Preqitems.get_by_id(pitemkey)
#preqitems[ix].rcode = request_code[ix]
Update: When trying
preqitems = ndb.get_multi([ndb.Key(Preqitems, k) for k in pitemkeys])
preqitems returns a list full of None values, as if the db couldn't find data for these keys.. I checked the keys and for some reason they are in unicode format, could that be the reason? They look like so.
[u'T-SQ-00301-0002-0001', u'U-T-MT-00334-0007-0002', u'U-T-MT-00334-0008-0001']
Probably you need to do: int(pitemkey) or str(pitemkey), depending if you are using integer or string id

Reading a list from a file in python 3

While trying to make a simple register/signup client only application for a personal project. I'm trying to load a list of users from a file, and compare them to a possible username. If the username already exists, the program will give them an error.
Here is a condensed clone of the code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.readline()
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
The user list is stored in a file so that it can opened, appended, and saved again, without being stored in the program. My current issue is that the userlist is saved as a string rather than an array. Is there a better way to do this? Thank you.
EDIT: Thanks to user lorenzo for a solution. My Friends are telling me to post a quick (really simple) copy of a for you guys who can't figure it out.
New code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.read() #Readline() changed to Read()
userlist = userlist.split('--') #This line is added
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
Example text file contents:
smith123--user1234--stacky
This line will seperate the string at the ('--') seperators and append each split part into an array:
userlist = userlist.split('--')
#Is used so that this (in the text file)
Smith123--user1234--stacky
#Becomes (in the program)
userlist = ['Smith123','user1234','stacky']
Sorry for the long post... Found it very interesting. Thanks again to Lorenzo :D.
userlist = t.readline()
reads one line from the file as a string. Iterating, then, gets characters in the string rather than words.
You should be able to get a list of strings (words) from a string with the split() method of strings or the more general re.split() function.

matlab array assignment

I'm trying to save all the files in a directory as an array of strings, like this:
files = {'hello.gdf'; 'hello2.gdf'...; ... 'etc.gdf'}
Since I have many directories, I want to do this automatically. This is my code:
gdffiles = dir(fullfile('D:', 'subject', '01', '*.gdf'))
for i=1:size(gdffiles)
files(i) = gdffiles(i).name;
end
I want to assign to files the name of the gdf files found, but I get this message:
??? Subscripted assignment dimension mismatch.
Error in ==> getFiles at 3
files(i) = gdffiles(i).name;
What am I doing wrong? Thanks!
The reason for error:
You try to assign files in the i-th place a string (char array) gdffiles(i).name. However, you are using an array-element assignment (round parenthesis ()). Therefore, you get an error: You can only assign a single char using files(i).
Possible solutions:
You should assign to files using curly braces - since files is a cell array:
files{i} = gdffiles(i).name;
You can achieve the same result without the loop by:
files = { gdffiles(:).name };
Check this solution
path = fullfile('D:', 'subject', '01', '*.gdf');
files = dir(path);
files = struct2cell(files);
files = files( 1, 1:end );
Have you tried this :
ListOfAllFiles = ls('*.gif')
Hope it helps

Resources