MATLAB only prints a part of my figure - matlab

I'm trying to print my figure in MATLAB, but it keeps screwing up and I have no idea why.
opslaan = figure(1);
plot(1:handles.aantal,handles.nauw,'-r','LineWidth',1.5);
xlabel(gca,sprintf('Framenummer (%g ms per frame)',60/handles.aantal));
ylabel(gca,'dB');
set(gca,'YGrid','on');
yAsMax = ceil( ceil(max(handles.nauw)) / 2) * 2;
axis([0 handles.aantal 0 yAsMax]);
pause(1);
print -dpng image.png
The first line is just plotting the data on my figure, then labeling x and y, turning on grid and calculating the y-axis like I want it. This all works great and MATLAB shows it like I want it in the figure window. When saving to .png / .jpeg / .eps, it goes wrong and only prints the bottom left corner (473x355 pixels), the rest just disappeared.
When exporting manually via File -> Save As, it works correctly.
How do I fix it?

The post Making Pretty Graphs contains an excellent tutorial about how to generate publication ready images from MATLAB figures.
In general, printing figures to image files programmatically should contain the following steps.
% Some data to be plotted
t1 = 0:0.1:4*pi ;
t2 = 0:0.01:4*pi ;
f1 = sin(t1) + randn(size(t1))/10 ;
f2 = sin(t2) + cos(t2.^2)/10 + randn(size(t2))/100 ;
% Define the styles to be used
linstyle_11 = {'LineStyle','--','Color',[.3 .6 .6],'LineWidth',1} ;
linstyle_12 = {'LineStyle','o','Color',[.3 .6 .6],'LineWidth',2,'MarkerSize',8,'MarkerFaceColor','m'} ;
linstyle_2 = {'Color',[.6 .3 .6],'LineWidth',3} ;
titleprops = {'FontSize',24,'FontWeight','bold',...
'FontName','FixedWidth','FontAngle','oblique',...
'Interpreter','None'} ;
axisprops = {'FontSize',20,'FontWeight','normal','FontName','FixedWidth'} ;
ylim_s = [-2 2] ;
% Set up the figure for PNG/JPEG export
canvas = [1 1 2048 1024] ;
fh = figure(1);
set( fh, ...
'PaperPositionMode','auto', ...
'Position',canvas ) ;
% Do the plotting and apply styles
ha1 = subplot(2,1,1);
hp11 = plot(t1,f1);
hold on
hp12 = plot(t1,f1);
hold off
title('subplot 1',titleprops{:})
xlabel('t',titleprops{:})
ylabel('f1',titleprops{:})
ha2 = subplot(2,1,2);
hp2 = plot(t2,f2);
title('subplot 2',titleprops{:})
xlabel('t',titleprops{:})
ylabel('f2',titleprops{:})
% finish appliing styles
set(hp11,linstyle_11{:}) ;
set(hp12,linstyle_12{:}) ;
set(hp2,linstyle_2{:}) ;
set(ha1,axisprops{:}) ;
set(ha2,axisprops{:}) ;
% Print
outfname = 'test' ;
print(fh,'-dpng',[outfname,'.png']) ;
% Sometimes it's better to use vector graphics ==>
% alter figure properties to allow proper PDF printouts.
set( fh, ...
'PaperSize', [29.71 13.01], ...
'PaperPosition', [0.01 0.01 29.7 13.0] ) ;
% print to pdf file
print(fh,'-dpdf',[outfname,'.pdf']) ;

Try using the following line instead of the print line you already have.
print(opslaan, '-dpng', 'image.png')
Another option would be to look into imwrite.

Related

Matlab - Multiple Plots in one Figure

I have a question about plots and subplots. I am iterating over some data and I am trying to get everything into a plot. It worked that every plot got written into one plot with hold on and figure but now I have to fit in regression lines. Therefore I want to plot everythiong into one figure but into different plots. This doesnt work as my plot looks a little bit weird.
My problem now is, that I cant find real helpful things on how to manage those plots other than using uicontrol. But I have never ever used uicontrol and I canĀ“t find enogh documentation to use it properly. I found this code:
figure(1)
panel1 = uipanel('Parent',1);
panel2 = uipanel('Parent',panel1);
set(panel1,'Position',[0 0 .99 1]);
set(panel2,'Position',[-1 0 2 1]);
set(gca,'Parent',panel2);
h = image; % <- Code for my own image goes here
s = uicontrol('Style','Slider','Parent',1,...
'Units','normalized','Position',[0 0 1 .025],...
'Value',1,'Callback',{#slider_callback1,panel2});
but all I get is a callback Problem. I dont know how to switch from a horizontal to a vertikal scrollbar and how to get my plots in there. The code manage it to write into the figure but in a very strange way that results in a similiar way as the subplotting everything.
I hope you can help me as good as always!
PS: This is my current code thats working (picture of the plot after it)
%% Clear Workspace
clc, clear all, close all; %
S = {} ;
F = [] ;
figure, hold on ;
%% Specify working directory
myFolder = '/home/k/karkarov92/Documents/Daten Igor/Zwick';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
%% Start Import from Mathilda aka. Z20
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.TXT'); % Change to whatever pattern needed.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
str = baseFileName;
level = wildcardPattern + "NIE_TOM_1_" ; % Name of the Pattern before the Name of the Sample
pat = asManyOfPattern(level);
str = extractAfter(str,pat);
Sample = erase(str,".TXT");
disp(Sample)
delimiterIn = ' '; %Extract thickness out of headers
headerlinesIn = 9;
G = importdata(fullFileName,delimiterIn,headerlinesIn);
G(3);
H = split(G(3));
K = H(2);
thickness = str2double(K)/100 ;
%read Table and extract Units
A = readtable(fullFileName,'decimal', ','); % without decimal and "," data import not with the right value wrong unit
Units = A(1,:);
A(1,:) = []; %units extracted and then stripped from table
%table = A(1:4,:); table output test
B = table2array(A); %change data from table to array
%disp(B(1:4,:)) ; %Array output test
strain = (B(:,2)- B(1,2)) / B(1,2); %strain calculated and stored in vector strain
stretch = strain +1 ; %stretch calculated and stored in vector strain
crossSection = 5. * thickness ; %calculate cauchy stress and cross section
cauchyStress = ((B(1:end,3).*stretch) / crossSection ) * 1000 ; %[GPa]
M = max(B) ; %exctract maxForce
maxForce = M(1,3) ;
F(end+1) = maxForce ;
S{k} = Sample ;
plot(stretch,cauchyStress)
xlabel('Stretch')
ylabel('Cauchy Stress')
title('Linear Regression for Modulus')
grid on
end

Bitmap-render part of plot during vector-graphics export in MATLAB

I have a quite complex function that I plot using fsurf with a reasonably high MeshDensity (I cannot go much lower than the default, which is 35). Exporting this figure (saveas(gcf, 'file.pdf', 'pdf');) results in a 20-something MB pdf file of very nice quality, which nonetheless renders terribly slow. I would like to reduce the file size and, most importantly, the complexity of this pdf file, without exporting the whole plot (by which I mean the whole MATLAB figure) as a bitmap. How can I do that?
The perfect answer would explain how I can convert the surface plot (by which I mean, just the colored function surface on the white background) into a bitmap while maintaining the vectorized nature of axes and labels.
Update: Here's an example of such a plot.
This is my function BitmapRender, which Bitmap-renders part of the figure:
%% Test Code
clc;clf;
Objects = surf(-4-2*peaks);
hold('on');
Objects(2 : 50) = plot(peaks);
Objects(51) = imagesc([20 40], [0, 5], magic(100));
hold('off');
ylim([0 10]);
zlim([-10 15]);
Objects(1).Parent.GridLineStyle = 'none';
view(45, 45);
set(gcf, 'Color', 'white');
rotate3d on
saveas(gcf, 'pre.pdf');
BitmapRender(gca, Objects(2 : 3 : end));
% BitmapRender(gca, Objects(2 : 3 : end), [0.25 0.25 0.5 0.5], false);
saveas(gcf, 'post.pdf');
The function itself is pretty simple, except for the (re-)handling of visibility, as pressing the space key (after rotating, zooming etc) re-renders the figure.
function BitmapRender(Axes, KeepObjects, RelativePosition, Draft, Key)
if nargin < 2
KeepObjects = [];
end
if nargin < 3
RelativePosition = [0 0 1 1];
end
if nargin < 4
Draft = false;
end
if nargin < 5
Key = '';
end
Figure = Axes.Parent;
FigureInnerWH = Figure.InnerPosition([3 4 3 4]);
PixelPosition = round(RelativePosition .* FigureInnerWH);
if isempty(Key)
OverlayAxes = axes(Figure, 'Units', 'Normalized', 'Position', PixelPosition ./ FigureInnerWH);
if Draft
OverlayAxes.Box = 'on';
OverlayAxes.Color = 'none';
OverlayAxes.XTick = [];
OverlayAxes.YTick = [];
OverlayAxes.HitTest = 'off';
else
uistack(OverlayAxes, 'bottom');
OverlayAxes.Visible = 'off';
end
setappdata(Figure, 'BitmapRenderOriginalVisibility', get(Axes.Children, 'Visible'));
Axes.CLimMode = 'manual';
Axes.XLimMode = 'manual';
Axes.YLimMode = 'manual';
Axes.ZLimMode = 'manual';
hManager = uigetmodemanager(Figure);
[hManager.WindowListenerHandles.Enabled] = deal(false);
set(Figure, 'KeyPressFcn', #(f, e) BitmapRender(gca, KeepObjects, RelativePosition, Draft, e.Key));
elseif strcmpi(Key, 'space')
OverlayAxes = findobj(Figure, 'Tag', 'BitmapRenderOverlayAxes');
delete(get(OverlayAxes, 'Children'));
OriginalVisibility = getappdata(Figure, 'BitmapRenderOriginalVisibility');
[Axes.Children.Visible] = deal(OriginalVisibility{:});
else
return;
end
if Draft
return;
end
Axes.Visible = 'off';
KeepObjectsVisibility = get(KeepObjects, 'Visible');
[KeepObjects.Visible] = deal('off');
drawnow;
Frame = getframe(Figure, PixelPosition);
[Axes.Children.Visible] = deal('off');
Axes.Visible = 'on';
Axes.Color = 'none';
if numel(KeepObjects) == 1
KeepObjects.Visible = KeepObjectsVisibility;
else
[KeepObjects.Visible] = deal(KeepObjectsVisibility{:});
end
Image = imagesc(OverlayAxes, Frame.cdata);
uistack(Image, 'bottom');
OverlayAxes.Tag = 'BitmapRenderOverlayAxes';
OverlayAxes.Visible = 'off';
end
Obviously, the solution is pixel-perfect in terms of screen pixels. Two pdf files (pre and post) look like this. Note that surface, image and some plot lines are bitmap rendered, but some other plot lines, as well as axes and labels are still vectorized.

Convert matlab line plot to stl

I'm trying to output Voronoi cells to a format which can be used for 3D printing.
MATLAB generates voronoi cells from lists of X and Y coordinates. My script generates such a list of points, but getting to a format I can export is seeming problematic.
My main hopes lie with stlwrite, http://www.mathworks.com/matlabcentral/fileexchange/20922-stlwrite-write-binary-or-ascii-stl-file
This function/script requires a surface to export.
function [lines, LineData, pOut] = makeSurfaceFromVorVerts(Lx, Ly, varargin)
p = inputParser;
addRequired(p,'Lx',...
#(x) (isequal(class(x),'double') && isequal(size(x,1),2)));
addRequired(p,'Ly',...
#(x) (isequal(class(x),'double') && isequal(size(x,1),2)));
defaultResolution = 100;
addOptional(p,'Resolution',defaultResolution,...
#(x) (isequal(class(x),'double') && isequal(size(x),[1 1])));
defaultBoundary = [0 110; 0 110];
addOptional(p,'Boundaries',defaultBoundary,...
#(x) (isequal(class(x),'double') && isequal(size(x),[2 2])));
parse(p,Lx,Ly,varargin{:});
pOut = p;
LX = p.Results.Lx;
LY = p.Results.Ly;
Bounds = p.Results.Boundaries;
% Strip high values
reducedXdat = [];
reducedYdat = [];
for i=1:size(LX,2)
if LX(1,i) > Bounds(1,1) && LX(1,i) < Bounds(1,2) && ... % X value of start of line
LX(2,i) > Bounds(2,1) && LX(2,i) < Bounds(2,2) && ... % Y value of start of line
LY(1,i) > Bounds(1,1) && LY(1,i) < Bounds(1,2) && ... % X value of end of line
LY(2,i) > Bounds(2,1) && LY(2,i) < Bounds(2,2), % Y value of end of line
reducedXdat = [reducedXdat, LX(:,i)];
reducedYdat = [reducedYdat, LY(:,i)];
end
end
% Initialise a grid of points
%sXnew = (Bounds(1,2) - Bounds(1,1)) * p.Results.Resolution;
%sYnew = (Bounds(2,2) - Bounds(2,1)) * p.Results.Resolution;
%Z = zeros(sXnew, sYnew,'uint8');
%for x=1:size(X,1)
% for y=1:size(Y,1)
% nX = floor(X(x)*p.Results.Resolution);
% nY = floor(Y(y)*p.Results.Resolution);
% Z(nX,nY) = 1;
% end
%end
%surface = Z;
%coords = [X,Y];
lines = line(reducedXdat,reducedYdat);
LineData = [reducedXdat; reducedYdat];
end
My processing script, above, takes the points generated by the command
[Lx, Ly] = voronoi(xValuesOfCellCentres, yValuesOfCellCentres);
along with an optional 'boundary' matrix (there's also a check for resolution, for the commented section) and then outputs lines.
I would like these lines to form the surface. I considered creating a mesh using a binary Z value (1 for points, 0 for everywhere else), but I don't know how I could also include the positions between points, ie those covered by the lines.
I expect that there is some relevant middle step I can take, to create a frame based on extrusion of the lines drawn (either by this script, which has cut away the extra lines to infinity, or by voronoi(X,Y), but I can't work it out.
Found a way to do this.
Changed the script, new script is pasted at the bottom.
Workflow goes:
Matlab (create line plot, then for i=1:size(lineHandles,1), set(lineHandles(i),'lineWidth',4),end). Change the line width as required.)
Save as .png file.
Gimp (crop file to a nice rectangle)
InkScape (open png file, click image, menu Path -> Trace Bitmap -> Color Quantization (2 colors) -> Drag the path aside (it shows path in the status bar at the bottom when you have this selected). Click image and delete. Place path (with nodes) back onto the page (there's an x/y coordinates setting in a toolbar at the top, set these both to 0.
Save as a .dxf file. To get these to input more nicely, use the extension provided at http://www.thingiverse.com/thing:14221. This should be installed by copying the .py and .inx files to /usr/share/inkscape/extensions (or similar)
Open in OpenSCAD using the command import("/path/to/filename.dxf");
This object can be extruded using the linear_extrude(height = x) where x is a height in mm (other lengths probably configurable)
Render using CGAL (F6 is the shortcut for this in OpenSCAD.)
Export to .stl file (menu Design > Export as STL...)
MATLAB script (edit as needed and take outputs as required, if you want the line handles you'll need to put in almost all of the output arguments (or reorder them):
%voronoiScriptHex generates voronoi cells in a hexagonal tesselation grid
% [X, Y, Fig, Axis, Lx, Ly, lH, lD] = voronoiScript(Bnd, Spc, D, ...)
%
% Output variables
% X is the x coordinate of the voronoi cell centres
% Y is the y coordinate of the voronoi cell centres
% Fig is the handle of the figure generated
% Axis is the handle of the axes used
% Lx gives the start and end x coordinates of the voronoi lines
% Ly gives the start and end y coordinates of the voronoi lines
% lH is the set of handles for the voronoi lines
% lD is constructed from [Lx; Ly], it is a [4 by Length] array
%
% Bnd specifies the boundaries for the region to be covered. It should be
% either one number, or a pair of numbers in a [1x2] vector, specifying
% [maxX, maxY]. 0 is taken as the minimum value.
%
% Spc specifies the average spacing. For a hex grid, it only accepts one
% value.
%
% D specifies the variation from a uniform grid. It is multiplied by a
% random number between -0.5 and 0.5 and added to the [x,y] coordinates
% of a point. If size(D) = [1x2], then the values are for [Dx, Dy].
%
% Optional arguments can be used to place some points exactly on the grid
% they would lie on with D[x/y] = 0. The first should be 'PartFixed' -
% this is a boolean and if true, some points are fixed to the grid.
%
% The second argument is 'FractionFixed'. This is an integer value
% (double class variables are accepted, but floor(arg) must be equal to
% (arg)). It specifies inversely how often points should be fixed, eg a
% value of 1 fixes every point, whilst a value of 5 fixes 1/5 of the
% points.
%
% PlotScatter is another boolean value, which sets if a scatter plot of
% the X,Y values corresponding to the cell centres should be included in
% the figure.
function [X, Y, Figure, Axis, Lx, Ly, lineHandles, lineData] = ...
voronoiScriptHex(Boundary, Spacing, Delta, varargin)
p = inputParser;
p.FunctionName = 'voronoiScript';
addRequired(p, 'Boundary', #checkTypes);
addRequired(p, 'Spacing', #isnumeric);
addRequired(p, 'Delta', #checkTypes);
defaultPart = false;
addOptional(p, 'PartFixed', defaultPart, #islogical);
defaultFraction = 2;
addOptional(p, 'FractionFixed', defaultFraction, #isAnInt);
defaultScatter = false;
addOptional(p, 'PlotScatter', defaultScatter, #islogical);
parse(p, Boundary, Spacing, Delta, varargin{:});
% Get values for boundaries and delta
% (Can be vectors or scalars)
if isequal(size(p.Results.Boundary),[1,2])
% Boundary is a vector [maxX, maxY]
BoundaryY = p.Results.Boundary(1,2);
else
BoundaryY = p.Results.Boundary(1,1);
end
if isequal(size(p.Results.Delta),[1,2])
% Delta is a vector [dX, dY]
DeltaY = p.Results.Delta(1,2);
else
DeltaY = p.Results.Delta(1,1);
end
Spacing = p.Results.Spacing;
BoundaryX = p.Results.Boundary(1,1);
DeltaX = p.Results.Delta(1,1);
D1 = [2*Spacing*cosd(30), Spacing];
numP = [ceil(BoundaryX/D1(1,1)) ceil(BoundaryY/D1(1,2))];
D2 = D1 ./ 2;
% Create the values
counter = 1;
xList(numP(1,1)*numP(1,2)) = 0;
yList(numP(1,1)*numP(1,2)) = 0;
for x=1:numP(1,1)
for y = 1:numP(1,2)
xList(counter) = (getPointValue(x, D1(1,1), DeltaX)-D2(1,1));
xList(counter+1) = getPointValue(x, D1(1,1), DeltaX);
yList(counter) = (getPointValue(y, D1(1,2), DeltaY)-D2(1,2));
yList(counter+1) = getPointValue(y, D1(1,2), DeltaY);
counter = counter + 2;
end
end
% Set some of the points to be without random change
if (p.Results.PartFixed),
for counter=1:p.Results.FractionFixed:size(xList,2),
[x, y] = getXYfromC(counter, numP(1,2));
xList(counter) = x*Spacing;
yList(counter) = y*Spacing;
end
end
X = xList;
Y = yList;
% Set manual ticks for the figure axes
ticksX = zeros(1,numP(1,1)+1);
for i=1:numP(1,1)+1,
ticksX(i) = i*D1(1,1);
end
ticksY = zeros(1,numP(1,2)+1);
for i=1:numP(1,2)+1,
ticksY(i) = i*D1(1,2);
end
BoundCoeff = 1.08;
Bounds = [0 BoundCoeff*BoundaryX; 0 BoundCoeff*BoundaryY];
% Give the figure a handle that is returned, and set axes values
Figure = figure;
Axis = axes;
axis equal;
minor = 'off';
gridtoggle = 'off';
set(Axis,'XTickMode','manual','YTickMode','manual', ...
'XGrid',gridtoggle,'YGrid',gridtoggle, ...
'XMinorGrid',minor,'YMinorGrid',minor, ...
'XTick',ticksX,'YTick',ticksY, ...
'XMinorTick',minor,'YMinorTick',minor, ...
'XLim',[0 Bounds(1,2)],'YLim',[0 Bounds(2,2)]);
%set(Axis,'XLim',[0 Bounds(1,2)],'YLim',[0 Bounds(2,2)]);
% Create the voronoi cells, returning the line points
[Lx, Ly] = voronoi(X,Y);
% Strip high values
counter = 1;
reducedXdat = zeros(2,size(Lx,2));
reducedYdat = zeros(2,size(Lx,2));
for i=1:size(Lx,2)
if Lx(1,i) > Bounds(1,1) && Lx(1,i) < Bounds(1,2) && ... % X value of start of line
Lx(2,i) > Bounds(2,1) && Lx(2,i) < Bounds(2,2) && ... % Y value of start of line
Ly(1,i) > Bounds(1,1) && Ly(1,i) < Bounds(1,2) && ... % X value of end of line
Ly(2,i) > Bounds(2,1) && Ly(2,i) < Bounds(2,2), % Y value of end of line
reducedXdat(:,counter) = Lx(:,i);
reducedYdat(:,counter) = Ly(:,i);
counter = counter + 1;
end
end
Lx = reducedXdat(:,1:counter-1);
Ly = reducedYdat(:,1:counter-1);
% Plot the voronoi lines
lineHandles = line(Lx, Ly);
% Set colours to black
if (1)
for i=1:size(lineHandles,1)
set(lineHandles(i),...
'LineWidth',3, ...
'LineSmoothing','on', ...
'Color',[0 0 0]);
end
end
lineData = [Lx; Ly];
if (p.Results.PlotScatter)
hold on;
scatter(X,Y);
end
end
function bool = checkTypes(arg)
bool = (isequal(class(arg),'double') && ...
(isequal(size(arg),[1,1]) || isequal(size(arg),[1,2])));
end
function bool = isAnInt(arg)
bool = (isequal(floor(arg),arg) && ...
isequal(size(arg),[1,1]) && ...
isnumeric(arg));
end
function val = getPointValue(intV, spacing, delta)
val = (((rand(1)-0.5)*delta)+(intV*spacing));
end
function [x,y] = getXYfromC(counter, sizeY)
x = floor(counter/sizeY)+1;
y = counter - ((x-1)*sizeY);
end
SCAD script file to place the voronoi cells within a pair of cylinders for 3D printing a grid. Edit as needed with path, or changes to shapes etc:
$fn = 360;
inkFile = "/path/to/my/file";
scl = 1.05; // Scale variable
transVec = [-100, -98, 0]; // Move the imported image pattern so that it's centred.
union(){
makeRing([0,0,3],inR=96, outR=99, height=6);
makeRing([0,0,1.5], inR=99, outR=102, height=3);
intersection() {
#linear_extrude(height = 6.05, convexity=40, center=false) // Removing the # will get rid of the overlay, which helps see where the grid is.
scale([scl, scl, 1])
translate(transVec)
import(inkFile);
makeCylinder([0,0,3], 96, 6, $fn=360);
}
}
module makeCylinder(centre, radius, height) {
translate(centre){
cylinder(h = height, r = radius, center=true);
}
}
module makeRing(centre,inR, outR, height) {
difference() {
makeCylinder(centre, outR, height);
makeCylinder(centre, inR, height+0.1);
}
}

MATLAB: cropping all images in a folder with different coordinates

i use the following MATLAB code to crop all images in a folder, it works perfectly but the problem is that it crops all the images with the same coordinates, what i want is to crop each image with specific coordinate. the coordinates of the images exist in a table in order, for example the coordinates of the image 1 are in row 1 and so on.
here is the code to get the coordinates in a table:
filename = 'fich.txt';
fid = fopen(filename);
A = textscan(fid, '%*s%*s%*s%*s%f%f%*f');
res = cell2mat(A);
res(isnan(res))=300;% remplacer les valeurs "NAN" dans la matrice par la valeur 300
fclose(fid);
and here is the code that cropps all images with the same coordinates:
% operating all pictures in a folder
clear all
close all
clc
dname_open = ('myfold') ; %Default Directory To be Opened
dname_save = ('myfold-cropped') ;
test = 0 ; % 0 - does every file in folder, 1 - only does first file
%% Set up basic file name path to read
top_file= [dname_open '\'] ; %Set up main database to open and look inside
ls_top_file = ls(top_file) ; %List Files inside main folder
c = cellstr(ls_top_file) ; %Turn cells from ls function into strings
cc = c(3:length(c)) ; %Set up a matrix without the . and .. produces by the ls function
S = size(cc) ; %Find the size of matrix containing names of files inside of main database
a = 1 ; %This counter is set to 3 to account for the . and .. at the beggining of each matrix created by ls
S(1)
while a <= S(1)
close all
file = char(cellstr([top_file char(cc(a))])) ; %File to be operated on
data_n = char(cc(a))
file_name = char(cc(a)) ;
% Operations on files in folder
imagename = (file_name) ;
%Input image image
fileToRead2 = [dname_open '\' imagename] ;
I = imread(fileToRead2);
%I2 = imcrop(I, rect) crops the image I. rect is a four-element position
%vector[xmin ymin width height] that specifies the size and position of the crop rectangle.
I2 = imcrop(I,[189.5 1.5 588 1022]);
imshow(I2,'Border','tight')
set(gcf, 'PaperPositionMode', 'auto');
h = gcf ;
saveas(h, [dname_save '\' 'z_' imagename ], 'pgm');
if test == 1
fprintf('breaking loop to set axis - test==1')
break
end
a = a+1 ;
end
thank you

Matlab Simulation: Point (symbol) Moving from start point to end point and back

I would like to create an animation to demonstrate LDPC coding which is based on Sum-Product Algorithm
So far I have created a graph which shows the connections between symbol nodes (left) and parity nodes (right)alt text http://img29.imageshack.us/img29/9780/ldpc.jpg and would like to animate points travelling from symbol to parity nodes and back.
The figure is drawn by executing the following method:
function drawVertices(H)
hold on;
nodesCount = size(H);
parityNodesCount = nodesCount(1);
symbolNodesCount = nodesCount(2);
symbolPoints = zeros(symbolNodesCount, 2);
symbolPoints(:, 1) = 0;
for i = 0 : symbolNodesCount - 1
ji = symbolNodesCount - i;
scatter(0, ji)
symbolPoints(i + 1, 2) = ji;
end;
parityPoints = zeros(parityNodesCount, 2);
parityPoints(:, 1) = 10;
for i = 0 : parityNodesCount - 1
ji = parityNodesCount - i;
y0 = symbolNodesCount/2 - parityNodesCount/2;
scatter(10, y0 + ji)
parityPoints(i + 1, 2) = y0 + ji;
end;
axis([-1 11 -1 symbolNodesCount + 2]);
axis off
%connect vertices
d = size(H);
for i = 1 : d(1)
for j = 1 : d(2)
if(H(i, j) == 1)
plot([parityPoints(i, 1) symbolPoints(j, 1)], [parityPoints(i, 2) symbolPoints(j, 2)]);
end;
end;
end;
So what I would like to do here is to add another method which takes start point (x and y) and end point as arguments and animates a travelling circle (dot) from start to end and back along the displayed lines.
I would appreciate if anyone of you could show the solution or suggest any useful tutorial about matlab simulations.
Thank you!
I believe the best way to learn is by example. So I suggest you look at the demo lorenz which comes with MATLAB:
edit lorenz
For other cool animations, look for orbits.m and swinger.m demos part of Cleve Moler's book: Experiments with MATLAB
I show here a simple animation of a point moving along a circular path. The hold idea boils down to using EraseMode set to xor, and updating XData and YData of the point for each iteration:
%# coordinates
t = (0:.01:2*pi)'; %# 'fix SO syntax highlight
D = [cos(t) -sin(t)];
%# setup a figure and axis
hFig = figure('Backingstore','off', 'DoubleBuffer','on');
hAx = axes('Parent',hFig, 'XLim',[-1 1], 'YLim',[-1 1], ...
'Drawmode','fast', 'NextPlot','add');
axis(hAx, 'off','square')
%# draw circular path
line(D(:,1), D(:,2), 'Color',[.3 .3 .3], 'LineWidth',1);
%# initialize point
h = line('XData',D(1,1), 'YData',D(1,2), 'EraseMode','xor', ...
'Color','r', 'marker','.', 'MarkerSize',50);
%# init text
hTxt = text(0, 0, num2str(t(1)), 'FontSize',12, 'EraseMode','xor');
i=0;
while true
i = rem(i+1,numel(t)) + 1; %# circular increment
set(h,'XData',D(i,1), 'YData',D(i,2)) %# update X/Y data
set(hTxt,'String',num2str(t(i))) %# update angle text
drawnow %# force refresh
if ~ishandle(h), return; end %# in case you close the figure
end
For a detailed explanation of the parameters used (EraseMode, Backingstore, DoubleBuffer, ..), refer to this animation guide
From the documentation for comet.m
t = 0:.01:2*pi;
x = cos(2*t).*(cos(t).^2);
y = sin(2*t).*(sin(t).^2);
comet(x,y);