save specific files with MATLAB commands - matlab

I'm trying to save models in oldest MATLAB versions as below
I look for each folder and subfolder to find any .mdl or .slx to save it as 2007b version
The problem I have is :
it works if I just look for one extension whereas I'm wondering
to do that on each .mdl and.slx .
the save_system takes too much
time
Do you know how could I get all .mdl and .slx and is there an optimized way to save ?
Thanks
rootPath = fullfile('M:\script\ytop','tables');
files = dir(rootPath );
for ii = 3:numel(files)
x = fullfile(rootPath ,files(ii).name);
cd(x);
mdl = { dir('*.mdl'),dir('*.slx')}; % here it works if only I set dir('*.mdl')
for jj = 1:numel(mdl)
load_system(mdl(jj).name);
save_system(mdl(jj).name,mdl(jj).name, 'SaveAsVersion','R2007b');
end
end

%here you used {} which created a cell array of two structs. cat creates a single struct which.
mdl=cat(1,dir('*.mdl'),dir('*.slx'));
for jj = 1:numel(mdl)
[~,sysname,~]=fileparts(mdl(jj).name);
load_system(mdl(jj).name);
%use only sysname without extension. R2007b is mdl only. You can't store files for R2007b in slx format
save_system(sysname,sysname, 'SaveAsVersion','R2007b');
%close system to free memory.
close_system(sysname);
end
Applying only the required fixes your code has one odd behaviour. For mdls the file is replaced with the original one, for slx a mdl is created next to the original one. You may want to add a delete(mdl(jj).name) after loading.

Related

pixelLabelDatastore from loaded image in workspace

I have multiple small *.mat files, each containing 4 input images (template{1:4} and a second channel template2{1:4}) and 4 output images (region_of_interests{1:4}), a binarized ('mask') image to train a deep neural network.
I basically followed an example on Mathworks and it suggests to use a function (in this example #matreader) to read in custom file formats.
However ...
It seems impossible to load multiple images from one *.mat file using any load function as it only allows one output, and imageDatastore doen't seem to allow loading data from workspace. How could this be achieved?
Similarly, it seems impossible to load a pixelLabelDatastore from a workspace variable. As a workaround I ended up saving the contents of my *.mat file to an image (using imwrite, saving to save_dir), and re-loading it from there (in this case, the function doesn't even allow to load *.mat files.). (How) can this be achieved without re-saving the file as image?
Here my failed attempt to do so:
%main script
image_dir = pwd; %location of *.mat files
save_dir = [pwd '/a/']; %location of saved output masks
imds = imageDatastore(image_dir,'FileExtensions','.mat','ReadFcn',#matreader); %load template (input) images
pxds = pixelLabelDatastore(save_dir,{'nothing','something'},[0 255]);%load region_of_interests (output) image
%etc, etc, go on to train network
%matreader function, save as separate file
function data=matreader(filename)
in=1; %give up the 3 other images stored in template{1:4}
load(filename); %loads template and template2, containing 4x input images each
data=cat(3,template{in},template2{in}); %concatinate 2 template input images in 3rd dimension
end
%generate example data for this question, will save into a file 'example.mat' in workspace
for ind=1:4
template{ind}=rand([200,400]);
template2{ind}=rand([200,400]);
region_of_interests{ind}=rand([200,400])>.5;
end
save('example','template','template2','output')
You should be able to achieve this using the standard load and save function. Have a look at this code:
image_dir = pwd;
save_dir = pwd;
imds = imageDatastore(image_dir,'FileExtensions',{'.jpg','.tif'});
pxds = pixelLabelDatastore(save_dir,{'nothing','something'},[0 255]);
save('images.mat','imds', 'pxds')
clear
load('images.mat') % gives you the variable "imds" and "pxds" directly -> might override previous variables
tmp = load('images.mat'); % saves all variables in a struct, access it via tmp.imds and tmp.pxds
If you only want to select the variables you want to load use:
load('images.mat','imds') % loads "imds" variable
load('images.mat','pxds') % loads "pxds" variable
load('images.mat','imds','pxds') % loads both variables
EDIT
Now I get the problem, but I fear this is not how it is going to work. The Idea behind the Datastore objects is, that it is used if the data is too big to fit in memory as a whole, but every little piece is small enough to fit in memory. You can use the Datastore object than to easily process and read multiple files on a disk.
This means for you: Simply save your images not as one big *mat file but as multiple small *.mat files that only contain one image.
EDIT 2
Is it strictly necessary to use an imageDatastore for this task? If not you can use something like the following:
image_dir = pwd;
matFiles = dir([image_dir '*.mat']);
for i=1:length(matFiles)
data = load(matFiles(i).name);
img = convertMatToImage(data); % write custom function which converts the mat input to your image
% or something like this:
% for j=1:4
% img(:,:,j) = cat(3,template{j},template2{j});
% end
% process image
end
another alternative would be to create a "image" in your 'matreader' which does not only have 2 bands but to simply put all bands (all templates) on top of each other providing a "datacube" and then in an second step after iterating over all small mat files and reading them splitting the single images out of the one bigger datacube.
would look something like this:
function data=matreader(filename)
load(filename);
for in=1:4
data=cat(3,template{in},template2{in});
end
end
and in your main file, you have to simply split the data into 4 pieces.
I have never tested it but maybe it is possible to return a cell instead of a matrix?
function data=matreader(filename)
load(filename);
data = cell(1,4)
for in=1:4
data{in}=cat(3,template{in},template2{in});
end
end
Not sure if this would work.
However, the right way to go forward from here really depends on how you plan to use the images from imds and if it is really necessary to use a imageDatastore.

Fast way of exporting the same figure n-times

I am trying to put together an animation in matlab. For this i am showing pictures containing a description of whats currently happening in the animation. So i am writing out pictures of my figures and later on put these together to an avi file again using matlab. For the description parts to "show up" long enough i use a simple loop in which the current figure is saved n-times. Unfortunatelly this process, though matlab does not have to calculate anything new, is the slowest one.
As the loop i use the following (h_f being the figure handle):
for delay = 1:80
export_fig (h_f,['-r' num2str(resolution)], ['C:\Users\Folder\Name_', '_' num2str(7700+delay) '.png'])
end
I just want to ask if there is any faster way. right now it kind of feels like matlab replots the fig each time before exporting it. So is there a way of plotting the figure once and simultaneously export it n-times?
Thanks for the help :)
If they are all really identical, then you can just copy the first file into the subsequent files. Your time will be limited by the speed of your disk drive and the size of your image files.
% Define some of the flags as variables. This'll make it clearer
% what you're doing when you revisit the code in a year.
% Flag for the resolution
resFlag = sprintf('-r%u', resolutions);
% Base folder
folder = 'C:\Users\Folder\';
% First file number
startnum = 7701;
% This is the pattern all the filenames will use
nameToken = 'Name_%u.png';
% First filename
firstFile = fullfile(folder, sprintf(nameToken, startnum));
% Export the first file
export_fig(h_f, resFlag, firstFile);
numCopies = 80;
% Copy the file
for delay = 2:numCopies
% Make a new filename
currentFile = fullfile(folder, sprintf(nameToken, startnum + delay));
% Copy the first file into the current filename.
copyfile(firstFile, currentFile);
end

How do I save nii files into one nii file using MATLAB

I have 360 3D-nifti files, I want to read all these files and save into one nifti file using Nifti Analyze tool that should yield a 4D file of large size. So far I have written following lines
clear all;
clc;
fileFolder=fullfile(pwd, '\functional');
files=dir(fullfile(fileFolder, '*.nii'));
fileNames={files.name};
for i=1:length(fileNames)
fname=fullfile(fileFolder,fileNames{i});
z(i)=load_nii(fname);
y=z(i).img;
temp(:,:,:,i) = make_nii(y);
save_nii(temp(:,:,:,i), 'myfile.nii')
fprintf('Iter: %d\n', i)
end
This code facilitates with a variable temp that is 4D struct and contains all the images. However, myfile.nii is just one single file its not all the images because its size is just 6mb it should be atleast one 1gb.
Can someone please have a look and let me know where I am wrong?
The way that you have it written, your loop is overwriting myfile.nii since you're calling save_nii every time through the loop with only the latest data. You'll want to instead call save_nii only once outside of the loop and save the entire temp variable at once.
for k = 1:numel(fileNames)
fname = fullfile(fileFolder, fileNames{k});
z(k) = load_nii(fname);
y(:,:,:,k) = z(k).img;
end
% Create the ND Nifti file
output = make_nii(y);
% Save it to a file
save_nii(output, 'myfile.nii')

importing variables from one file to another MATLAB

I have 2 matlab programs : prog1.m and prog2.m
I have to use a 2-D matrix M in both programs.
I have loaded the matrix in prog1.m (manually from a TEXT FILE).
I have to run both the programs ~100 times (for different matrix each time) . So now i have ran prog1.m 100 times , every time with different matrix .
Now is turn of prog2.m but i don't want to load matrix manually again.
I have the saved (100 copies of) prog1.m which contains M to be used in prog2.m also . Is there a method to load M from prog2.m to prog1.m ?
I want to add some code in prog2.m which automatically loads M from prog1.m .
PS: I am very new to MATLAB
If prog1 and prog2 are not already functions, rewrite them as functions. For example, the first line in them may look like:
function [out1 out2] = prog1(M)
function out = prog2(M)
Then, write a third function which, given a filename, loads the data, calls prog1 and prog2 and optionally saves the data in an appropriate form (you can use fileparts and fullfile to automatically create a new filename based on the input - e.g. given data101.txt, return data101_proc.mat. Bare bones of such a function would be along these lines:
function M = prog3(fname)
M = load(fname); % or whatever method is required for loading this data
%call prog1 and prog2
[out1 out2] = prog1(M);
out3 = prog2(M);
%make new filename
[fpath,fname2,ext] = fileparts(fname);
fname_out = fullfile(fpath, [fname2,'_out','.mat']);
%save data - depends on what outputs are and what you need to do with them later
save(fname_out, 'out1','out2','out3','M');
end
Finally, as babaea mentioned, you can use ls or dir, make up a list of the files you want to use, and create a loop which calls the above function on each file in turn.
The most efficient way of doing what you want to do is to read directly from the text file using textscan:
http://www.mathworks.co.uk/help/matlab/ref/textscan.html
If the formatting in the text files are the same, you can read from one file at a time, do your process then change the name and run again.
You can make the process more automated by changing the name of the file from which data is read dynamically in a loop around your main program. But the way to do this depends on the name of the text files.

Saving image using MATLAB

I made a program in MATLAB to generate images with different specifications, but each time I change one of theses specifications I had to re-save the image under a different name and path. So, I made a for loop to change these specifications, but I don't know how I can make MATLAB save the generated image with different names and different paths...
How can I write a program to make MATLAB save multiple generated images with different names and different paths as a part of for–loop?
Put something like this at the end of your loop:
for i = 1:n
<your loop code>
file_name=sprintf('%d.jpg',i); % assuming you are saving image as a .jpg
imwrite(your_image, file_name); % or something like this, however you choose to save your image
end
If you want to save JPEG, PNG etc., then see #AGS's post. If you want to save FIG files, use
hgsave(gcf, file_name)
instead of the imwrite line. There's also
print('-djpeg', file_name) %# for JPEG file (lossy)
print('-dpng', file_name) %# for PNG file (lossless)
as an alternative for imwrite.
Since I wanted to save the plots in my loop in a specific folder in my present working directory (pwd), I modified my naming routine as follows:
for s = 1:10
for i = 1:10
<loop commands>
end
end
% prints stimuli to folder created for them
file_name=sprintf('%s/eb_imgs/%0.3f.tif',pwd,s(i)); % pwd = path of present working
% directory and s(i) = the value
% of the changing variable
% that I wanted to document
file_name = /Users/Miriam/Documents/PSYC/eb_imgs/0.700.tif % how my filename appears
print('-dtiff', '-r300', file_name); % this saves my file to my desired location
matlab matlab-path