I am importing some data from the excel and the code looks like this:
Code:
%Import Data
filename = 'Stocks.xlsx';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);
The excel file looks like this:
When I read in the data, A looks like this:
I thought when the headerlineIn = 1, the first line should not read. Why is it that it is being read? How to avoid this?
Need some guidance..
How I thought your code is alright.
With your example file and your code I get a struct A.
A = importdata('Stocks.xlsx',' ',1);
In A.data.Sheet1 is all the data correctly read:
And in A.textdata.Sheet1 the appears what you posted you get.
So the problem must be something I can't reproduce.
Alternatively you could try if xlsread works for you.
B = xlsread('Stocks.xlsx',1)
I get the same result as before.
I finally get your problem, you're not concerned about the data, you really want to skip the first line of the header in the means of textdata.
Well headerlinesIn just signalizes importdata when your data starts, respectively when it should start to read actual data. Everything else, which is then declared not to be data, is put into A.textdata.Sheet1, also the first line. So the code works as intended.
If you want to get rid of the first line of your header, you could apply the following line:
N = 2; %// number of columns before data starts
A.textdata.Sheet1 = {A.textdata.Sheet1{headerlinesIn+1:end,1:N}};
Related
i'm trying to do something like that:
get_num_of_ones = "('1'):rep(%d)"
print(get_num_of_ones:format(24))
but i get the following result: ('1'):rep(24) and not 24 times the number 1.
how can I do it in this way so that i will get 111...11 (24 times the number 1) ?
The simplest, most straightforward, efficient and readable way to achieve what you want is simply to pass your number directly to string.rep; there is no need to format source code here:
get_num_of_ones = ('1'):rep(24)
print(get_num_of_ones)
If there is the artificial constraint that it needs to be achieved by formatting a source code template, you need to use load/loadstring:
get_num_of_ones = "return ('1'):rep(%d)" -- you need the "return" to make it a valid chunk, and to be able to get the result out
local source = get_num_of_ones:format(24) -- formatted source code
local chunk = assert(load(source)) -- load the source code; gives us a "chunk" (function) if there was no syntax error
local retval = chunk()
print(retval)
I am looking for a M-Function that returns the currently opened Excel Spreadsheet Filename without the directory and extension.
i.e. If the spreadsheet that is opened is located here:
C:\HPCLMHSTLI_930.XLSX
I would like:
HPCLMHSTLI_930
Note: I got this working using a Custom M Function that reads a Settings Table which has two Cells defined with the following:
=MID(CELL("filename"),SEARCH("[",CELL("filename"))+1, SEARCH("]",CELL("filename"))-SEARCH("[",CELL("filename"))-1)
=LEFT(B3,(SEARCH(".",B3)-1))
So I am NOT looking for this solution. This solution just seems like a lot of work and that there should be a more elegant M-Language function that would return the currently opened spreadsheet filename.
I didn't quite follow how you got the path - I guess that is Cell("fileName"), but with a bit of fiddling with M Code, I came up with the following:
let
x = "C:\HPCLMHSTLI_930.XLSX",
y=Text.AfterDelimiter(x,"\"),
z=Text.BeforeDelimiter(y,".")
in
z
This seems to do the trick. Since a file name can have more than 1 period in it, this may be too simple, but maybe this can work if your filenames are simple enough.
But this can be improved by wrapping this in a function in the following way:
let
ParseFileName = (x) =>
let
y=Text.AfterDelimiter(x,"\"),
z=Text.BeforeDelimiter(y,".")
in z
in
ParseFileName
and then call that using something like this:
let
Source = ParseFileName("C:\HPCLMHSTLI_930.XLSX")
in
Source
I found two more possible answers.
This first is a bit more sophisticated than the one above. In this case, we grab the substring starting after the first "\" and the last "."
let
x = "C:\HPCLMHSTLI_930.XLSX",
y = Text.PositionOf(x,"\", Occurrence.First),
z = Text.PositionOf(x,".", Occurrence.Last),
a = Text.Middle(x,y+1,z-y-1)
in
a
There probably should be if statements in case one of these characters are not found.
I found one final solution that could also work in the simpler cases.
let
x = "C:\HPCLMHSTLI_930.XLSX",
z = Text.BetweenDelimiters(x,"\",".")
in
z
M gives us a bunch of choices on this.
I'm going to use this as sample data to simplify the problem:
data_set_1
I want to split the contents of this csv according to Column A - DEPARTMENT and place them on new csv's named after the department.
If it were done in the same workbook (so it can fit in one image) it would look like:
data_set_2
My initial thought was something pretty simple like:
CSV.foreach('test_book.csv', headers: true) do |asset|
CSV.open("/import_csv/#{asset[1]}", "a") do |row|
row << asset
end
end
Since that should take care of the logic for me. However, from looking into it, CSV#foreach does not accept file access rights as second parameter, and it gets an error when I run it. Any help would be appreciated, thanks!
I don't see why you would need to pass file access rights to CSV#foreach. This method just reads the CSV. How I would do this is like so:
# Parse the entire CSV into an array.
orig_rows = CSV.parse(File.read('test_book.csv'), headers: true)
# Group the rows by department.
# This becomes { 'deptA' => [<rows>], 'deptB' => [<rows>], etc }
groups = orig_rows.group_by { |row| row[1] }
# Write each group of rows to its own file
groups.each do |dept, rows|
CSV.open("/import_csv/#{dept}.csv", "w") do |csv|
rows.each do |row|
csv << row.values
end
end
end
A caveat, though. This approach does load the entire CSV into memory, so if your file is very large, it wouldn't work. In that case, the "streaming" approach (line-by-line) that you show in your question would be preferrable.
I have the code mentioned below in matlab. I want to write all the 162 rows and 4 columns calculated into an excel file.
When i use xlswrite in the code i get only one row and 4 columns as the value of P gets overwritten in each iterative step.
If i use another loop inside the for loop the execution time increase drastically. Please help to least write the values of P into an array which i can later write into excel file(when i tried 'In an assignment A(I) = B, the number of elements in B and I must be the same' error appeared.)
please help
function FitSMC_BC
clc
% Parameters: P(1)=theta_S; P(2)=theta_r; P(3)=psib; P(4)=lamda;
smcdata=xlsread('asimdata');
nn=length(smcdata)-1;
for i=1:nn
psi=smcdata(:,1);
thetaObs=smcdata(:,i+1);
%Make an initial guess:
Pini=[0.5 0.1 -1 1.5];
P=fminsearch(#ObFun,Pini,[],psi,thetaObs);
disp(['result',num2str(i),': P=',num2str(P)]);
theta=Gettheta(P,psi);
end
function OF=ObFun(P,psi,thetaObs)
theta=Gettheta(P,psi);
OF=sqrt(mean((theta - thetaObs).^2));
function theta=Gettheta(P,psi)
SoilPars.theta_S=P(1);
SoilPars.theta_r=P(2);
SoilPars.psib=P(3);
SoilPars.lamda=P(4);
[theta]=thetaFun(psi,SoilPars);
function [theta]=thetaFun(psi,SoilPars)
theta_S=SoilPars.theta_S;
theta_r=SoilPars.theta_r;
psib=SoilPars.psib;
lamda=SoilPars.lamda;
theta=theta_r+((theta_S-theta_r)*((psib./psi).^lamda));
theta(psi>psib)=theta_S;
You can modify the P line with
P(i,:) = fminsearch(#ObFun,Pini,[],psi,thetaObs);
P will store each calculation (4 element vector) in a new line.
You may also initialise P before the for loop with P = nan(nn, 4);
Then write P in an Excel file using xlswrite.
I haven't studied your code in-depth, but as far as I can tell, you have two options:
Create a matrix P and use xlswrite on the entire matrix. This seems to me like the most reasonable approach.
Use xlswrite1 from the fileexchange in a loop. This will increase execution time a bit, but not nearly as much as using regular xlswrite as it is specially deigned to be used inside loops. The reason why it is so much faster is because it only opens and closes the Excel-file once, whereas the regular xlswrite opens and closes it every time you call the function.
You seem to know how to use indexing so I'm not sure why you're simply doing something like this:
P = zeros(size(smcdata,1),nn)
for i=1:nn
...
P(:,i) = fminsearch(#ObFun,Pini,[],psi,thetaObs);
disp(['result',num2str(i),': P=',num2str(P(:,i))]);
theta = Gettheta(P(:,i),psi); % Why is this here? Are you writing it to file too?
end
xlswrite('My_FileName.xls',P);
Or you could call xlswrite on each iteration of the loop (probably slower) and append the new data using something like this:
for i=1:nn
...
P = fminsearch(#ObFun,Pini,[],psi,thetaObs);
disp(['result',num2str(i),': P=',num2str(P)]);
theta = Gettheta(P,psi); % Why is this here? Are you writing it to file too?
xlswrite('My_FileName.xls',P,1,['A' int2str((i-1)*size(P,2)+1)]);
end
Of course your code isn't runnable so you'll have to debug any other little errors. Also, since smcdata seems to be a matrix rather than a vector, you should be careful using length with it. You probably should use size.
Question : Is there a way to have direct access to a specific cell in vtkPolyData structure?
I'm using vtkPolyData to store sets of lines, say L.
Currently, I'm using GetLines() to know the number of lines in L. Then, I have to use GetNextCell to go through this set of lines using a "while" loop.
Current code is something like:
vtkSmartPointer<vtkPolyData> a;
...
vtkSmartPointer<vtkCellArray> lines = a->GetLines();
...
while(lines->GetNextCell(numberOfPoints, pointIds) != 0)
-> I'd like to be able to work directly on a specific line by doing something like:
myline = a[10];
doSomething(myline);
you could get an access to a specific cell using vtkDataSet::GetCell(vtkIdType cellId) function