Export Values from MATLAB workspace to CSV or XLS - excel

I would like to be able to export the Value from each Name in the Workspace using MATLAB.
I have some questions, which then sets the variables in the workspace. I have tried xlswrite but I have been unsuccessful in being able to export the file. I don't think that it would export just the value, which I would like it to do.
% Construct a questdlg with three options
choiceprepq = 'Which animal do you like?';
choiceprep = questdlg('Which animal do you like?', 'Which animal do you like?', 'Dog', 'Cat','Fish');
% Handle response
switch choiceprep
case 'Dog'
disp([choiceprep ' Dog Selected.'])
case 'Cat'
disp([choiceprep ' Cat Selected.'])
case 'Fish'
disp([choiceprep ' Fish Selected.'])
end
alldata= whos('global');
filename='Test.xls';
xlswrite(filename,alldata)
Is there any way to export the question and the value which the user selects from the question boxes as an Excel file? Not the name of the variable, choiceprep, but its value.
An example in this case would be:

First of all, unless you actually declare choiceprepq and choiceprep as global variables, using whos('global') won't give you those two. It's not necessary here anyways, because you already know the variables you want.
Also, you're using questdlgwrong, you need to specify your default answer, so it should be like this:
% syntax : button = questdlg('qstring','title', default)
choiceprepq = 'Which animal do you like?';
choiceprep = questdlg(choiceprepq, choiceprepq, 'Dog', 'Cat', 'Fish', 'Dog');
When you do xlswrite, it actually only writes the values held by the variables. In your case, you can easily store the question and answer into an xls file by this:
filename = 'Test.xls';
xlswrite(filename, {choiceprepq, choiceprep})
The curly braces turn the two variables into a 1x2 cell array whose values can be easily written into xls file by xlswrite.
xlswrite does not seem to work properly on Mac OS. Here's a MATLAB file exchange submission that's supposed to help : http://www.mathworks.com/matlabcentral/fileexchange/38591-xlwrite--generate-xls-x--files-without-excel-on-mac-linux-win

Related

how do I get rid of leading/trailing spaces in SAS search terms?

I have had to look up hundreds (if not thousands) of free-text answers on google, making notes in Excel along the way and inserting SAS-code around the answers as a last step.
The output looks like this:
This output contains an unnecessary number of blank spaces, which seems to confuse SAS's search to the point where the observations can't be properly located.
It works if I manually erase superflous spaces, but that will probably take hours. Is there an automated fix for this, either in SAS or in excel?
I tried using the STRIP-function, to no avail:
else if R_res_ort_txt=strip(" arild ") and R_kom_lan=strip(" skåne ") then R_kommun=strip(" Höganäs " );
If you want to generate a string like:
if R_res_ort_txt="arild" and R_kom_lan="skåne" then R_kommun="Höganäs";
from three variables, let's call them A B C, then just use code like:
string=catx(' ','if R_res_ort_txt=',quote(trim(A))
,'and R_kom_lan=',quote(trim(B))
,'then R_kommun=',quote(trim(C)),';') ;
Or if you are just writing that string to a file just use this PUT statement syntax.
put 'if R_res_ort_txt=' A :$quote. 'and R_kom_lan=' B :$quote.
'then R_kommun=' C :$quote. ';' ;
A saner solution would be to continue using the free-text answers as data and perform your matching criteria for transformations with a left join.
proc import out=answers datafile='my-free-text-answers.xlsx';
data have;
attrib R_res_ort_txt R_kom_lan length=$100;
input R_res_ort_txt ...;
datalines4;
... whatever all those transforms will be performed on...
;;;;
proc sql;
create table want as
select
have.* ,
answers.R_kommun_answer as R_kommun
from
have
left join
answers
on
have.R_res_ort_txt = answers.res_ort_answer
& have.R_kom_lan = abswers.kom_lan_answer
;
I solved this by adding quotes in excel using the flash fill function:
https://www.youtube.com/watch?v=nE65QeDoepc

How to read specific sheet with multiple columns with readmatrix in matlab?

so I am trying to read multiple sheets in excel using matlab by this function:
Data_mat=readmatrix('DATA_I.xlsx');
I tried a couple of things using additional info, bu seems not correct.
If you want the output to be a matrix, use that command. On the other hand, if you want to read tables (considering the column name), you can use the readtable command.
I generated a dummy excel file that only contains 2 sheets with some numbers there. If you want to read the matrices, use the readmatrix, or if you want tables, just change that function to readtable. Both functions have the same argument structure.
% Define the file name
FileName = "MatrixesInFile.xlsx";
% Get the sheets in the excel file
Sheets = sheetnames(FileName);
% Generate the variable with the matrices
myMatrices = struct;
% Read the matrices and store it in the struct
for n=1:length(Sheets)
% Get evaluated sheet
eval_sheet = Sheets{n};
% Get the matrix
values = readmatrix(FileName,'Sheet',eval_sheet);
% Create a field in the struct and store the matrix there
myMatrices.(eval_sheet) = values;
end
% Print the variable
myMatrices

How can I change a variable in a .txt template, if I have more than 5000 different values for this variable in an excel table?

I have an excel table with a column called 'interface', and what I want to do is a code that pull each interface value : Port-channel47, Port-channel46,etc... and put it in my .txt template replacing the {interface} part that i have in my txt template.
the value I want to change in the .txt template is "{interface}"
I tried this code:
but I get lost when i want to pull the data.
Anyone can help me? thank you so much in advance
Use string template:
from string import Template
with open('template.txt') as fp:
template = Template(fp.read())
for interface, group in df.groupby('Interface'):
file_name = interface.replace('/', '_') + '_output.txt'
with open(file_name, 'w') as fp:
content = template.substitute(interface=interface)
fp.write(content)
When you iterate over a DataFrameGroupBy object, it returns a 2-tuple containing the key of the group, and all rows matching that key.
A second thing to worry about is that / is not a valid path under most OSes I know so you must replace it with some other character (I chose a _).

Struct name from variable in Matlab

I have created a structure containing a few different fields. The fields contain data from a number of different subjects/participants.
At the beginning of the script I prompt the user to enter the "Subject number" like so:
prompt='Enter the subject number in the format SUB_n: ';
SUB=input(prompt,'s');
Example SUB_34 for the 34th subject.
I want to then name my structure such that it contains this string... i.e. I want the name of my structure to be SUB_34, e.g. SUB_34.field1. But I don't know how to do this.
I know that you can assign strings to a specific field name for example for structure S if I want field1 to be called z then
S=struct;
field1='z';
S.(field1);
works but it does not work for the structure name.
Can anyone help?
Thanks
Rather than creating structures named SUB_34 I would strongly recommend just using an array of structures instead and having the user simply input the subject number.
number = input('Subject Number')
S(number) = data_struct
Then you could simply find it again using:
subject = S(number);
If you really insist on it, you could use the method proposed in the comment by #Sembei using eval to get the struct. You really should not do this though
S = eval([SUB, ';']);
Or to set the structure
eval([SUB, ' = mydata;']);
One (of many) reasons not to do this is that I could enter the following at your prompt:
>> prompt = 'Enter the subject number in the format SUB_n: ';
>> SUB = input(prompt, 's');
>> eval([SUB, ' = mydata;']);
And I enter:
clear all; SUB_34
This would have the unforeseen consequence that it would remove all of your data since eval evaluates the input string as a command. Using eval on user input assumes that the user is never going to ever write something malformed or malicious, accidentally or otherwise.

Lua: Parsing and Manipulating Input with Loops - Looking for Guidance

I am currently attempting to parse data that is sent from an outside source serially. An example is as such:
DATA|0|4|7x5|1|25|174-24|7x5|1|17|TERW|7x5|1|9|08MN|7x5|1|1|_
This data can come in many different lengths, but the first few pieces are all the same. Each "piece" originally comes in with CRLF after, so I've replaced them with string.gsub(input,"\r\n","|") so that is why my input looks the way it does.
The part I would like to parse is:
4|7x5|1|25|174-24|7x5|1|17|TERW|7x5|1|9|08MN|7x5|1|1|_
The "4" tells me that there will be four lines total to create this file. I'm using this as a means to set the amount of passes in the loop.
The 7x5 is the font height.
The 1 is the xpos.
The 25 is the ypos.
The variable data (172-24 in this case) is the text at these parameters.
As you can see, it should continue to loop this pattern throughout the input string received. Now the "4" can actually be any variable > 0; with each number equaling a set of four variables to capture.
Here is what I have so far. Please excuse the loop variable, start variable, and print commands. I'm using Linux to run this function to try to troubleshoot.
function loop_input(input)
var = tonumber(string.match(val, "DATA|0|(%d*).*"))
loop = string.match(val, "DATA|0|")
start = string.match(val, loop.."(%d*)|.*")
for obj = 1, var do
for i = 1, 4 do
if i == 1 then
i = "font" -- want the first group to be set to font
elseif i == 2 then
i = "xpos" -- want the second group to be set to xpos
elseif i == 3 then
i = "ypos" -- want the third group to be set to ypos
else
i = "txt" -- want the fourth group to be set to text
end
obj = font..xpos..ypos..txt
--print (i)
end
objects = objects..obj -- concatenate newly created obj variables with each pass
end
end
val = "DATA|0|4|7x5|1|25|174-24|7x5|1|17|TERW|7x5|1|9|08MN|7x5|1|1|_"
print(loop_input(val))
Ideally, I want to create a loop that, depending on the var variable, will plug in the captured variables between the pipe deliminators and then I can use them freely as I wish. When trying to troubleshoot with parenthesis around my four variables (like I have above), I receive the full list of four variables four times in a row. Now I'm having difficulty actually cycling through the input string and actually grabbing them out as the loop moves down the data string. I was thinking that using the pipes as a means to delineate variables from one another would help. Am I wrong? If it doesn't matter and I can keep the [/r/n]+ instead of each "|" then I am definitely all for that.
I've searched around and found some threads that I thought would help but I'm not sure if tables or splitting the inputs would be advisable. Like these threads:
Setting a variable in a for loop (with temporary variable) Lua
How do I make a dynamic variable name in Lua?
Most efficient way to parse a file in Lua
I'm fairly new to programming and trying to teach myself. So please excuse my beginner thread. I have both the "Lua Reference Manual" and "Programming in Lua" books in paperback which is how I've tried to mock my function(s) off of. But I'm having a problem making the connection.
I thank you all for any input or guidance you can offer!
Cheers.
Try this:
val = "DATA|0|4|7x5|1|25|174-24|7x5|1|17|TERW|7x5|1|9|08MN|7x5|1|1|_"
val = val .. "|"
data = val:match("DATA|0|%d+|(.*)$")
for fh,xpos,ypos,text in data:gmatch("(.-)|(.-)|(.-)|(.-)|") do
print(fh,xpos,ypos,text)
end

Resources