Delete Excel Figures from Matlab - matlab

I would like to directly delete all the figures in an excel file from MATLAB. I can select all the figures using activex but I cant' figure out a way to delete them.
My code:
filename_out = 'Libraries\Documents\TEST.xlsx'; % filename
Excel = actxserver('Excel.Application'); % open the connection
set(Excel,'Visible',1);
Excel.Workbooks.Open(filename_out); % open excel file
worksheets = Excel.sheets;
numSheets = worksheets.Count; % count the number of sheets
for s = 1 : numSheets % do a loop for all sheets
worksheets.Item(s).Shapes.SelectAll; % select the figure
% How to delete selection? *
end
Thanks for any help!

Within your loop, do something like
myshapes = worksheets.Item(s).Shapes;
for j = myshapes.Count:-1:1
myshapes.Item(j).Delete
end
Note that we're counting down from myshapes.Count to 1, as the count goes down each time you remove one.

Related

How to plot different files information in a different graph using a loop

I have a program in octave that read a file, then some functions takes different parts of that file to make some plots. But now I want to read many files and creates a plot for each file. The program that I have, read these files, but at the moment of plotting, it creates multiple plots, but with the same data file (first data file).
I already try using hold on and hold off, but it did not work.
myfiles = dir('*.lvm'); % To load every file of .lvm
%%% - To read files
for i = 1:length(myfiles) % Loop with the number of files
files = myfiles(i).name; % Structure element with file's names
n(:,:,i)= dlmread(files,'',2,1);% To read the contain
CM1N1 = n(:,2,:);
CM2N1 = n(:,3,:);
CM3N1 = n(:,4,:);
CM4N1 = n(:,5,:);
N1m(:,:,:) = [CM1N1 CM2N1 CM3N1 CM4N1];
%========================================================================%
% Calling all functions
%========================================================================%
%--- Function config_horizontale which plot X position and has the respective info
[Nmean1m]=config_horizontale(n,N1m);
end
'''
AND THIS IS A PART OF THE FUNCTION
''' function [Nmean1m]=config_horizontale(n,N1m)
%=========================================================================%
% To plot
%=========================================================================%
Nmean1m = mean(N1m);
xM = 20:20:80;
i=1;
figure
plot(xM,Nmean1m(:,:,i),'-+')
end
As 'i' is the number of files, I need,first to plot the first file, then the second one and so on and on. Thanks in advance.
Here you will find an example of the file
LabVIEW Measurement
-0.004110 0.003667 -0.007486 0.003185 -0.005198 -0.005292
-0.001542 0.001109 -0.002435 0.003185 -0.005198 0.003184
-0.006678 0.006224 -0.002435 0.000531 -0.010615 0.000358
-0.006678 -0.001448 -0.007486 0.005839 -0.005198 -0.002467
-0.006678 0.003667 -0.004961 0.005839 -0.007906 -0.002467
-0.006678 0.003667 -0.002435 0.008493 -0.007906 0.003184

Appending to an excel in matlab

I am following up on my own question. By using:
excelWorkbook.SaveAs('figtest.xlsx');
I am overwriting the existing excel. I have created a function which uses the code to save two images to excel. Now I want to iterate over a number of images, process each image and then save the result alongside the original image to an excel. Obviously calling the function each iteration is a bad idea since, each iteration is deleting the results of former iterations.
How can I add the current data to the excel file without deleting any former data?
Is there a better way to do this?
Note that the data is images and not simple numeric data.
Create a COM server once, iterate over the images and place them in the desired cells, quit the server and then delete the server object.
Building from my previous answer, here is a working example with 5 of many built-in images:
%Some sample images
im{1}=imread('peppers.png');
im{2}=imread('cameraman.tif');
im{3}=imread('pears.png');
im{4}=imread('greens.jpg');
im{5}=imread('bag.png');
excel = actxserver('Excel.Application'); % Create server object
excelWorkbook = excel.Workbooks.Add(1); % Add a workbook
excelSheet = excel.ActiveSheet; % Get the active sheet
f = figure('visible','off'); % To not show the images in MATLAB
dpi = get(groot, 'ScreenPixelsPerInch'); % Get screen dpi
for k=1:5
imshow(im{k});
print(gcf, sprintf('-r%d', dpi), ... % Print the figure at the screen resolution
'-clipboard', '-dbitmap'); % to the clipboard as a bitmap
%Adjust the cell names where you want to paste the images as desired
excelSheet.Range(['B',num2str(k)]).PasteSpecial();
%Unlocking aspect ratio to adjust height and width of the image according to the cell
excelSheet.Shapes.Item(k).LockAspectRatio='msoFalse';
excelSheet.Shapes.Item(k).Width=excelSheet.Range(['B',num2str(k)]).Width;
excelSheet.Shapes.Item(k).Height=excelSheet.Range(['B',num2str(k)]).Height;
end
excelWorkbook.SaveAs('figtest.xlsx'); % Save workbook to a file
excelWorkbook.Close(); % Close workbook
excel.Quit(); % Quit server
excel.delete(); % Delete server object
which gives:
One approach is to place each set of images in its own sheet, creating new sheets in the Excel file as needed. Here's some sample code, modified from my previous answer:
% Start COM server:
excel = actxserver('Excel.Application');
excelWorkbook = excel.Workbooks.Add(1);
excelWorksheets = excelWorkbook.Worksheets;
% Initializations:
dpi = get(groot, 'ScreenPixelsPerInch');
for iSheet = 1:nIterations % Based on how many image sets you process
% Get a blank sheet:
if (iSheet == 1)
excelSheet = excel.ActiveSheet;
else
excelSheet = excelWorksheets.Add([], excel.ActiveSheet, 1);
end
% Load, process, and plot your images here:
...
% Paste image into sheet and adjust cell size:
print(hFigure, sprintf('-r%d', dpi), '-clipboard', '-dbitmap');
excelSheet.Range('B2').PasteSpecial();
excelSheet.Range('B2').RowHeight = excelSheet.Shapes.Item(1).Height;
widthScale = excelSheet.Range('B2').ColumnWidth./...
excelSheet.Range('B2').Width;
excelSheet.Range('B2').ColumnWidth = excelSheet.Shapes.Item(1).Width.*widthScale;
end
% Save and close workbook and stop COM server:
excelWorkbook.SaveAs('figtest.xlsx');
excelWorkbook.Close();
excel.Quit();
excel.delete();
Adding data to an excel file is not well defined: creating new sheets or adding data to an existing one?
Therefore, you probably need the following methodology:
Open the existing excel file (to which you want to add data)
Add the new data to the opened excel file
Save this edited excel file
Just found this here:
xlApp = actxserver('Excel.Application');
xlApp.visible = 1;
%Open the the spreadsheet
xlworkbook = xlApp.Workbooks.Open('figtest.xlsx');
xlsheet = xlworkbook.ActiveSheet;
mydata=randn(1,3);
data=xlsread('figtest.xlsx');
%Determine last row
last=size(data,1);
newRange=last+1;
xlCurrRange = xlsheet.Range(['A', num2str(newRange),':C', num2str(newRange)]);
xlCurrRange.Value2 = mydata;
%Save and Close the Excel File
invoke(xlworkbook,'Save');
invoke(excelApp,'Quit');
delete(excelApp);
Also, you may want to try this script from the File Exchange.

Find which line of a .dat file MATLAB is working on

I have a MATLAB script that reads a line from a text file. Each line of the text file contains the filename of a CSV. I need to keep track of what line MATLAB is working on so that I can save the data for that line in a cell array. How can I do that?
To illustrate, the first few lines of my .dat file looks like this:
2006-01-003-0010.mat
2006-01-027-0001.mat
2006-01-033-1002.mat
2006-01-051-0001.mat
2006-01-055-0011.mat
2006-01-069-0004.mat
2006-01-073-0023.mat
2006-01-073-1003.mat
2006-01-073-1005.mat
2006-01-073-1009.mat
2006-01-073-1010.mat
2006-01-073-2006.mat
2006-01-073-5002.mat
2006-01-073-5003.mat
I need to save the variable site_data from each of these .mat files into a different cell of O3_data. Therefore, I need to have a counter so that O3_data{1} is the data from the first line of the text file, O3_data{2} is the data from the second line, etc.
This code works, but it's done without using the counter so I only get the data for one of the files I'm reading in:
year = 2006:2014;
for y = 1:9
flist = fopen(['MDA8_' num2str(year(y)) '_mat.dat']); % Open the list of file names - CSV files of states with data under consideration
nt = 0; % Counter will go up one for each file loaded
while ~feof(flist) % While end of file has not been reached
fname = fgetl(flist);
disp(fname); % Stores name as string in fname
fid = fopen(fname);
while ~feof(fid)
currentLine = fgetl(fid);
load (fname, 'site_data'); % Load current file. It is all the data for one site for one year
O3_data = site_data;
% Do other stuff
end
fclose(fid);
end
fclose(flist);
end
If I add the time index part, MATLAB is telling me that Subscript indices must either be real positive integers or logicals. nt is an integer so I don't know what I'm doing wrong. I need the time index so that I can have O3_data{i} in which each i is one of the files I'm reading in.
year = 2006:2014;
for y = 1:9
flist = fopen(['MDA8_O3_' num2str(year(y)) '_mat.dat']); % Open the list of file names - CSV files of states with data under consideration
nt = 0;
while ~feof(flist) % While end of file has not been reached
fname = fgetl(flist);
fid = fopen(fname);
while ~feof(fid)
currentLine = fgetl(fid);
nt = nt+1; % Time index
load (fname, 'site_data'); % Load current file. It is all the data for one site for one year
O3_data{nt} = site_data;
% Do other stuff
end
fclose(fid);
end
fclose(flist);
end
Try the following:
years = 2006:2014;
for y=1:numel(years)
% read list of filenames for this year (as a cell array of strings)
fid = fopen(sprintf('MDA8_O3_%d_mat.dat',years(y)), 'rt');
fnames = textscan(fid, '%s');
fnames = fnames{1};
fclose(fid);
% load data from each MAT-file
O3_data = cell(numel(fnames),1);
for i=1:numel(fnames)
S = load(fnames{i}, 'site_data');
O3_data{i} = S.site_data;
end
% do something with O3_data cell array ...
end
Try the following - note that since there is an outer for loop, the nt variable will have to be initialized outside of that loop so that we don't overwrite data from previous years (or previous j's). We can avoid the inner while loop since the just read file is a *.mat file and we are using the load command to load its single variable into the workspace.
year = 2006:2014;
nt = 0;
data_03 = {}; % EDIT added this line to initialize to empty cell array
% note also the renaming from 03_data to data_03
for y = 1:9
% Open the list of file names - CSV files of states with data under
% consideration
flist = fopen(['MDA8_O3_' num2str(year(y)) '_mat.dat']);
% make sure that the file identifier is valid
if flist>0
% While end of file has not been reached
while ~feof(flist)
% get the name of the *.mat file
fname = fgetl(flist);
% load the data into a temp structure
data = load(fname,'site_data');
% save the data to the cell array
nt = nt + 1;
data_03{nt} = data.site_data;
end
fclose(flist); % EDIT moved this in to the if statement
end
end
Note that the above assumes that each *.dat file contains a list of *.mat files as illustrated in your above example.
Note the EDITs in the above code from the previous posting.

Read through and save files with different filenames

I have a list of CSV files. The filenames of these files have been stored in the form [year '_MDA8_mat.dat']. I want to read in each of these files into MATLAB and save the output. How can I write the code so that each year is considered in turn and the output .mat file will be saved for each year?
Here's what I have for reading in one of the files:
flist = fopen('2006_MDA8_mat.dat'); % Open the list of file names - CSV files of states with data under consideration
nt = 0; % Counter will go up one for each file loaded
while ~feof(flist) % While end of file has not been reached
for i = 1:27299 % Number of files
fname = fgetl(flist); % Reads next line of list, which is the name of the next data file
disp(fname); % Stores name as string in fname
nt = nt+1; % Time index
load (fname, 'site_data'); % Load current file. It is all the data for one site for one year
O3_data{i} = site_data;
% Do some more stuff
end
save ('2006_MDA8_1990_2014.mat', '-v7.3')
I tried to write a for loop like this:
year = 2006:2014
for y = 1:9
flist = fopen([year(y) '_MDA8_mat.dat']);
nt = 0; % Counter will go up one for each file loaded
while ~feof(flist) % While end of file has not been reached
for i = 1:1500 % Number of files
% Same as above
end
end
save ([year '_MDA8_1990_2014.mat'], '-v7.3')
end
However, when I run this, it doesn't do the same thing as it did for the one file script. I'm not quite sure where the error occurs, but MATLAB tells me there's an error with feof, which doesn't seem to make sense.
When combining numbers and strings, you need to do a num2str on the number:
[num2str(year) '_MDA8_1990_2014.mat']

Parsing a data file in matlab

I have a text file with two columns of data. I want to split this file and save it as two individual strings in matlab, but I also need to stop copying the data when I meet an identifier in the data then stat two new strings.
For example
H 3
7 F
B B
T Y
SPLIT
<>
Where SPLIT <> is where I want to end the current string.
I'm trying to use fopen and fscanf, but struggling to get it to do what I want it to.
I tried the following script on the example you provided and it works. I believe the comments are very self explanatory.
% Open text file.
fid = fopen('test.txt');
% Read the first line.
tline = fgetl(fid);
% Initialize counter.
ii = 1;
% Check for end string.
while ~strcmp(tline, 'SPLIT')
% Analyze line only if it is not an empty one.
if ~strcmp(tline, '')
% Read the current line and split it into column 1 and column 2.
[column1(ii), column2(ii)] = strread(tline, ['%c %c']);
% Advance counter.
ii = ii + 1;
end
% Read the next line.
tline = fgetl(fid);
end
% Display results in console.
column1
column2
% Close text file.
fclose(fid);
The key functions here are fgetl and strread. Take a look at their documentation, it has some very nice examples as well. Hope it helps.