Matlab - Multiple Plots in one Figure - matlab

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

Related

MATLAB to Scilab conversion: mfile2sci error "File contains no instruction"

I am very new to Scilab, but so far have not been able to find an answer (either here or via google) to my question. I'm sure it's a simple solution, but I'm at a loss. I have a lot of MATLAB scripts I wrote in grad school, but now that I'm out of school, I no longer have access to MATLAB (and can't justify the cost). Scilab looked like the best open alternative. I'm trying to convert my .m files to Scilab compatible versions using mfile2sci, but when running the mfile2sci GUI, I get the error/message shown below. Attached is the original code from the M-file, in case it's relevant.
I Searched Stack Overflow and companion sites, Google, Scilab documentation.
The M-file code follows (it's a super basic MATLAB script as part of an old homework question -- I chose it as it's the shortest, most straightforward M-file I had):
Mmax = 15;
N = 20;
T = 2000;
%define upper limit for sparsity of signal
smax = 15;
mNE = zeros(smax,Mmax);
mESR= zeros(smax,Mmax);
for M = 1:Mmax
aNormErr = zeros(smax,1);
aSz = zeros(smax,1);
ESR = zeros(smax,1);
for s=1:smax % for-loop to loop script smax times
normErr = zeros(1,T);
vESR = zeros(1,T);
sz = zeros(1,T);
for t=1:T %for-loop to carry out 2000 trials per s-value
esr = 0;
A = randn(M,N); % generate random MxN matrix
[M,N] = size(A);
An = zeros(M,N); % initialize normalized matrix
for h = 1:size(A,2) % normalize columns of matrix A
V = A(:,h)/norm(A(:,h));
An(:,h) = V;
end
A = An; % replace A with its column-normalized counterpart
c = randperm(N,s); % create random support vector with s entries
x = zeros(N,1); % initialize vector x
for i = 1:size(c,2)
val = (10-1)*rand + 1;% generate interval [1,10]
neg = mod(randi(10),2); % include [-10,-1]
if neg~=0
val = -1*val;
end
x(c(i)) = val; %replace c(i)th value of x with the nonzero value
end
y = A*x; % generate measurement vector (y)
R = y;
S = []; % initialize array to store selected columns of A
indx = []; % vector to store indices of selected columns
coeff = zeros(1,s); % vector to store coefficients of approx.
stop = 10; % init. stop condition
in = 0; % index variable
esr = 0;
xhat = zeros(N,1); % intialize estimated x signal
while (stop>0.5 && size(S,2)<smax)
%MAX = abs(A(:,1)'*R);
maxV = zeros(1,N);
for i = 1:size(A,2)
maxV(i) = abs(A(:,i)'*R);
end
in = find(maxV == max(maxV));
indx = [indx in];
S = [S A(:,in)];
coeff = [coeff R'*S(:,size(S,2))]; % update coefficient vector
for w=1:size(S,2)
r = y - ((R'*S(:,w))*S(:,w)); % update residuals
if norm(r)<norm(R)
index = w;
end
R = r;
stop = norm(R); % update stop condition
end
for j=1:size(S,2) % place coefficients into xhat at correct indices
xhat(indx(j))=coeff(j);
end
nE = norm(x-xhat)/norm(x); % calculate normalized error for this estimate
%esr = 0;
indx = sort(indx);
c = sort(c);
if isequal(indx,c)
esr = esr+1;
end
end
vESR(t) = esr;
sz(t) = size(S,2);
normErr(t) = nE;
end
%avsz = sum(sz)/T;
aSz(s) = sum(sz)/T;
%aESR = sum(vESR)/T;
ESR(s) = sum(vESR)/T;
%avnormErr = sum(normErr)/T; % produce average normalized error for these run
aNormErr(s) = sum(normErr)/T; % add new avnormErr to vector of all av norm errors
end
% just put this here to view the vector
mNE(:,M) = aNormErr;
mESR(:,M) = ESR;
% had an 'end' placed here, might've been unmatched
mNE%reshape(mNE,[],Mmax)
mESR%reshape(mESR,[],Mmax)]
figure
dimx = [1 Mmax];
dimy = [1 smax];
imagesc(dimx,dimy,mESR)
colormap gray
strESR = sprintf('Average ESR, N=%d',N);
title(strESR);
xlabel('M');
ylabel('s');
strNE = sprintf('Average Normed Error, N=%d',N);
figure
imagesc(dimx,dimy,mNE)
colormap gray
title(strNE)
xlabel('M');
ylabel('s');
The command used (and results) follow:
--> mfile2sci
ans =
[]
****** Beginning of mfile2sci() session ******
File to convert: C:/Users/User/Downloads/WTF_new.m
Result file path: C:/Users/User/DOWNLO~1/
Recursive mode: OFF
Only double values used in M-file: NO
Verbose mode: 3
Generate formatted code: NO
M-file reading...
M-file reading: Done
Syntax modification...
Syntax modification: Done
File contains no instruction, no translation made...
****** End of mfile2sci() session ******
To convert the foo.m file one has to enter
mfile2sci <path>/foo.m
where stands for the path of the directoty where foo.m is. The result is written in /foo.sci
Remove the ```` at the begining of each line, the conversion will proceed normally ?. However, don't expect to obtain a working .sci file as the m2sci converter is (to me) still an experimental tool !

Turning a plot3 into a surf in MATLAB

I have several csv files and I plotted them using plot3 to create the following image:
Now I would like to turn this into a surface plot because I would like to colour the plot according to height. I made the following with scatter3:
clearvars;
files = dir('*.csv');
name = '\epsilon_{y} over time for Vertical section';
des_col_1 = 'Vertical section.epsY []';
des_col_2 = 'Length [mm]';
set(gca,'FontSize',20)
a = gca;
ii = 1;
x_data = [];
y_data = [];
z_data = [];
tStart = tic;
for file = files'
csv = xlsread(file.name);
[n,s,r] = xlsread(file.name);
des_cols = {des_col_1,des_col_2};
colhdrs = s(1,:);
[~,ia] = intersect(colhdrs, des_cols);
colnrs = flipud(ia);
file.name = n(:,colnrs);
file.name = file.name(1:end,:);
x_data = [x_data; file.name(:,2)];
y_data = [y_data; ones(size(file.name(:,2))).*ii];
z_data = [z_data; file.name(:,1)];
ii = ii+1;
end
tEnd = toc(tStart);
fprintf('%d minutes and %f seconds\n',floor(tEnd/60),rem(tEnd,60));
view(40,40);
zlabel({'True strain (%)'});
xlabel({'Length along sample (mm)'});
ylabel({'Stage'});
title({name});
scatter3(a,x_data,y_data,z_data,10,z_data);
colormap(jet); %# or other colormap
which gives me this
That was made with a smaller set of data than the first one as a test. It does almost what I want but I was wondering if there was a way to generate a true 3D surface from all my data. I can create a matrix with x, y, and z values for all points and I tried to replace scatter3(a,x_data,y_data,z_data,10,z_data); with
[X,Y] = meshgrid(x_data,y_data);
f = scatteredInterpolant(x_data,y_data,z_data);
Z = f(X,Y);
surf(a,X,Y,Z);
but the plot that I get does not look very good
I'm pretty sure there's something wrong with the interpolation but I'm not very good with surfaces so I don't know how to correct it.
The reason surf is giving you the error is you are creating long nx1 arrays Where n = number of points per file times number of files. For x,y,& z_data and you need them into a matrix instead. So try the following changes:
for file = files'
<snipped out for length>
x_data = [x_data; file.name(:,2).'];
y_data = [y_data; ones(1,numel(file.name(:,2))).*ii];
z_data = [z_data; file.name(:,1).'];
ii = ii+1;
end
This should make x, y, and z_data the size nxm (n = number of files, m = number points per file).
Then you should be able to just do
surf(x_data,y_data,z_data)

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

error with "The matrix MSG in ENCODE must have K columns"

im working on a video steganography using LSB technique..im using traffic.avi and xylophone.mpg as the cover medium and when im using the licence.txt file (in the attach file) to encode into the video it runs well however when im using a short messsage for the input text it shows an error which is
"The matrix MSG in ENCODE must have K columns." and sometimes when use short text it gives error "msg is too long to encode"
i have no idea what does this 2 set of coding means and how to edit the code to make it possible to encode a short msg...below this is some of the code that i guess relate to this problem
num2add = 80-length(msg); % Number of spaces to add to end of MSG.
if num2add < 0, error('This message is too long to encode.'), end
newmsg = [msg,repmat(' ',1,num2add)]; % 80 chars always encoded.
msgmat = dec2bin(newmsg)-48; % Each row is a bin. rep. of an ascii char.
and also this coding
if m_msg == 1
type_flag = 2; % binary vector
[msg, added] = vec2mat(msg, k);
elseif m_msg ~= k
error('comm:encode:InvalidMatrixColumnSize','The matrix MSG in ENCODE must have K columns.');
BELOW THIS IS THE FULL ENCODE CODING continue after the first part of the above coding!
B = pic1(:,:,1); [piclngth pichght] = size(B); % Choose the first page.
dim1 = piclngth-2; dim2 = pichght-3; keyb = key(end:-1:1);
rows = cumsum(double(key));
columns = cumsum(double(keyb)); % Coord pairs for KEY (rows,columns)
A = zeros(dim1,dim2); % This matrix will house the hiding points.
A = crtmtrx(A,rows,columns,dim1,dim2,key);
idx = find(A==1); % This same index will be used for pic matrix.
for vv = 1:80 % This is the encoder.
for uu = 1:8
if msgmat(vv,uu)==1;
if rem(B(idx(uu+8*(vv-1))),2)==0
if(frame==1)
disp('some pixel value of original frame');
B(idx(uu+8*(vv-1)))
end
B(idx(uu+8*(vv-1))) = B(idx(uu+8*(vv-1)))+1;
if(frame==1)
disp('some pixel value of stegno video frame');
B(idx(uu+8*(vv-1)))
end
end
elseif rem(B(idx(uu+8*(vv-1))),2)==1
if(frame==1)
disp('some pixel value of original frame');
B(idx(uu+8*(vv-1)))
end
B(idx(uu+8*(vv-1))) = B(idx(uu+8*(vv-1)))-1;
if(frame==1)
disp('some pixel value of stegno video frame');
B(idx(uu+8*(vv-1)))
end
end
end
end
global newpic;
newpic = pic1; newpic(:,:,1) = B;
f(frame) = im2frame(newpic);
end
frameRate = get(vidObj,'FrameRate');
movie2avi(f,'stegano_video.avi','compression','None', 'fps', 20);
success = 1;
function A = crtmtrx(A,rows,columns,dim1,dim2,key)
% Creates the matrix used to find the points to hide the message.
jj = 1; idx = 1;
while 640 > length(idx) % Need 560 points to hide 80 characters.
for ii = 1:length(rows)
if rows(ii) < dim1
rows(ii) = rem(dim1,rows(ii))+1;
else
rows(ii) = rem(rows(ii),dim1)+1;
end
if columns(ii) < dim2
columns(ii) = rem(dim2,columns(ii))+1;
else
columns(ii) = rem(columns(ii),dim2)+1;
end
A(rows(ii),columns(ii)) = 1;
end
rows = jj*cumsum(double(columns))+round(dim2/2); % Each pass is diff.
columns = jj*cumsum(double(rows))+round(dim1/2);
if jj > ceil(640/length(key))+2 % Estimate how many iters. needed.
idx = find(A==1);
end
jj = jj+1;
end
this is some of the input text and the right one is the encypted txt
The code that triggers the error is pretty clear:
num2add = 80-length(msg); % Number of spaces to add to end of MSG.
if num2add < 0, error('This message is too long to encode.'), end
So basically you will get the error as soon as there are more than 80 characters in msg. I am not sure whether the 80 is meaningfull, you can try to increase it but that may break something else.

MATLAB only prints a part of my figure

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.