Occasionally, figure size is not set properly in Matlab - matlab

I tried to set same figure size for several images using for loop in matlab and save in png
But some (usually one) of them has different size.
In below code, I tried to save image in (48,64).
Why some figure sizes are not set properly as I commanded?
nMarker = 5;
mark = ['o', 's', 'd', '^', 'p'];
nSize = 3;
mSize = [9, 18, 27];
nRow = 48;
nCol = 64;
BG = zeros(nRow, nCol);
idxStage = 2;
numAction = 1;
numPositionX = 4;
numPositionY = 4;
xtrain = [1,2,3,4];
ytrain = [1,2,3,4];
xpos = [20, 30, 40, 50];
ypos = [8, 18, 28, 38];
nStepS = 10;
nStepB = 10;
nStep = nStepS + nStepB;
for a = 1
for x = 1:numPositionX
for y = 1:numPositionY
for obj = 1:nMarker
for s = 1:nSize
obj_command = x*1000 + y*100 + obj*10 + s;
fig1 = figure(1);
imagesc(BG)
hold on
scatter(xpos(x), ypos(y), mSize(s), mark(obj), 'k', 'filled')
axis off
set(fig1, 'Position', [500, 500, 64, 48]);
set(gca,'position',[0 0 1 1],'units','normalized')
F = getframe(gcf);
pause(0.05)
[X, Map] = frame2im(F);%
tmp_frame = rgb2gray(X);
tmp_im_fn = sprintf('tmp/image_seq%04d.png',obj_command);
imwrite(tmp_frame, tmp_im_fn)
clf
end
end
end
end
end

I found some trick to solve the problem for now.
I put,
fig1 = figure(1);
drawnow
in front of the for loop and it seems all sizes are equal now.
But still waiting for better solution...

Related

Problem with normalizing a function with likelihood

I have a problem with the following code. In the evidence part, the value is very small so, in the end, the probabilities are not calculated. I need to normalize it, but in which part should it be?
The code in MATLAB is:
clear all; close all; clc;
randn('seed', 1234);
resistivities = [50 200 2000 1500];
thicknesses = [500 100 200];
Par_real = [resistivities, thicknesses];
dataFreq = logspace(log10(0.001), log10(1000), 100);
[Ydata, phase] = modelMT2(Par_real, dataFreq);
sigma = 0.1;
Yexp = Ydata + sigma*randn(size(Ydata));
plot(dataFreq, Yexp, '.'); hold on; plot(dataFreq, Ydata, '-')
nsamples = 20000;
R1 = 5;
R2 = 2050;
P1 = 25;
P2 = 500;
Resis = R1 + (R2-R1)*rand(nsamples, 7);
Profs = P1 + (P2-P1)*rand(nsamples, 6);
for ii=1:nsamples
par3C = [Resis(ii, 1:3), Profs(ii, 1:2)];
par4C = [Resis(ii, 1:4), Profs(ii, 1:3)];
par5C = [Resis(ii, 1:5), Profs(ii, 1:4)];
par7C = [Resis(ii, 1:7), Profs(ii, 1:6)];
Like_M3C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par3C);
Like_M4C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par4C);
Like_M5C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par5C);
Like_M7C(ii) = log_likelihood(#modelMT2, dataFreq, Yexp, sigma, par7C);
end
figure()
subplot(1, 2, 1)
plot(exp(Like_M5C))
subplot(1, 2, 2)
hist(exp(Like_M5C))
Evidencia(1) = mean(exp(Like_M3C));
Evidencia(2) = mean(exp(Like_M4C));
Evidencia(3) = mean(exp(Like_M5C));
Evidencia(4) = mean(exp(Like_M7C));
Denominador = sum(Evidencia);
PPMM = Evidencia/Denominador;
fprintf('La probabilidad de los modelos : \n');
fprintf('--------------------------------\n');
fprintf('Modelo M3C: %.4f \n', PPMM(1));
fprintf('Modelo M4C: %.4f \n', PPMM(2));
fprintf('Modelo M5C: %.4f \n', PPMM(3));
fprintf('Modelo M7C: %.4f \n', PPMM(4));
figure()
model = [1, 2, 3, 4];
bar(model, PPMM), grid on
ylim([0, 1])
xlabel('Modelo')
ylabel('Probabilidad del modelo')
function [LogPDF_post] = log_likelihood(Mod, xx, data, sigma, oldpar)
erro = (Mod(oldpar, xx) - data)';
LogPDF_post = -0.5 * erro' * 1/sigma^2 * erro;
end
I have tried to normalize the likelihood as follows, but it doesn't work. It gives equal probability in all cases.
function [LogPDF_norma] = log_likelihood(Mod, xx, data, sigma, oldpar)
erro = (Mod(oldpar, xx) - data)';
LogPDF_post = -0.5 * erro' * 1/sigma^2 * erro;
LogPDF_norma = (1/max(LogPDF_post))*LogPDF_post;
end

How to display a group of subplots as a movie?

I have 30 heatmap subplots. How could I present these subplots as an animation or a movie (i.e. one heatmap each 0.5 seconds)?
The subplots are obtained with the following code:
var = {'GeneX','GeneY','GeneZ'};
syms x y z S
alpha_x = 3.9e-2;
beta_x = 6.1;
z_x = 1.3e-5;
n_zx = 2.32;
alpha_y= 4.3e-2;
beta_y = 5.7;
x_y = 7.9e-4;
n_xy = n_zx;
delta_y = 1.05;
x_z = 12e-2;
n_xz = n_zx;
y_z = 11e-3;
n_yz = n_zx;
delta_z = 0.2;
ACDC_X = (alpha_x+beta_x*S)/(1+S+(z/z_x)^n_zx)-x;
ACDC_Y = (alpha_y+beta_y*S)/(1+S+(x/x_y)^n_xy)-delta_y*y;
ACDC_Z = 1/(1+(x/x_z)^n_xz+(y/y_z)^n_yz)-delta_z*z;
ACDCsys_div = [ ACDC_X, ACDC_Y, ACDC_Z ];
J = jacobian(ACDCsys_div,[x;y;z]);
Jsolnew(x,y,z,S) = [J];
%%Construction of the coordinates as a matrix
A = load('matlab.mat','unnamed');% import data from directory
a2 = struct2array(A);% coordinates of the equilibrium point.
numofGraphs = 80;
bx = length(a2(1,1:numofGraphs));
%% Construction of the heatmaps
figure;
hmapax = ceil(sqrt(bx));
for kk = 1:bx %bnx %All bin windows = iteration
JacACDCnew(:,:,kk) = Jsolnew(a2(1,kk),a2(2,kk),a2(3,kk),a2(4,kk));
ACDC_HmapJnew = double(JacACDCnew(:,:,kk));
subplot(hmapax,hmapax,kk);%
heatmap(var,var,ACDC_HmapJnew,'ColorScaling','log');
S = a2(4,kk);
title(['Jac','s=',num2str(S)]);
end
Consider the following example:
function q56130816
% Load some data:
frames = imread('https://i.stack.imgur.com/03kN8.gif');
frames(frames > 1) = 2;
% Create subplots:
figure('WindowState','maximized'); subplot(2,4,1);
for ind1 = 1:8
subplot(2,4,ind1);
imagesc(frames(:,:,1,ind1)); axis image; axis off;
end
colormap([255 255 255; 188 188 188; 244 128 36]./255);
% Capture subplots as frames:
for ind1 = 8:-1:1
frameHolder(ind1) = getframe( subplot(2, 4 ,ind1) );
end
% Play as movie:
hF = figure(); movie(hF, frameHolder, 20, 2);
Which will turn:
Into:
As you can see, in the example above I used getframe, but frames can also be captured using print, as mentioned in the getframe docs. Frames can also be exported to a video file, as explained here.
Animation credit: frames were screen-captured from Johan Lindell's Codepen example.

Making colorbar tick labels a string above and below bar, remove ticks - Matlab

I am trying to reproduce the colorbar below for my chart. Specifically it is the string colorbar axis title (above and below the colorbar) that I am struggling with, the rest seems fine.
Below is my current code:
time_begin = [1981, 1, 1, 0,0,0];
time_end = [2010,12,31,23,0,0];
years = (time_begin(1):time_end(1))';
nyears = length(years);
TXx1 = randi(100, 288, 192, 30);
lat = rand(192, 1);
lon = rand(288, 1);
time = rand(30,1);
M = numel(lon);
N = numel(lat);
slope1 = zeros(M, N);
intercept1 = zeros(M, N);
T = numel(time);
x = ([ones(T, 1) years]);
for i = 1 : M
for j = 1 : N
y1 = squeeze(TXx1(i, j, :));
c = regress(y1, x);
intercept1(i, j) = c(1);
slope1(i, j) = c(2);
end
end
TXx2 = randi(100, 288, 192, 30);
slope2 = zeros(M, N);
intercept2 = zeros(M, N);
T = numel(time);
x = ([ones(T, 1) years]);
for i = 1 : M
for j = 1 : N
y2 = squeeze(TXx2(i, j, :));
c = regress(y2, x);
intercept2(i, j) = c(1);
slope2(i, j) = c(2);
end
end
figure()
set(gcf, 'color', 'w');
temp = [slope1(:) slope2(:)];
temp(temp == 0) = NaN;
[Q,Qc] = hist3(temp,'Nbins',[100 100],'CDataMode','auto');
Qx = cell2mat(Qc(1));
Qy = cell2mat(Qc(2));
Q = Q';
Q = Q./trapz(Qy,trapz(Qx,Q,2));
surf(Qx,Qy,Q,'FaceColor','interp','EdgeColor','none')
grid off
set(gca, 'Fontsize', 12, 'Fontweight', 'Bold'); %added
cmap = jet(500);
cmap(1,:) = [1,1,1];
colormap(cmap);
h=colorbar;
set(h,'position',[.91 .34 .031 .475]) %[xposition yposition width height].
set(get(h,'ylabel'),'string','Point density');
set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',});
view(0,90)
Here is my current colourbar:
Replace this line:
set(h,'XTickLabel',{'Low',' ',' ',' ',' ','High',});
with:
h.YTick = h.Limits;
h.YTickLabel = {'Low', 'High'};
This makes two tick-lines and two tick labels. By setting YTicks of the colorbar to its limits, the tick-lines get overlapped by colorbar boundary. So these get hidden and now there is no need to remove them.
However there is this TickLength property which can be used otherwise i.e.
h.TickLength = 0;
Result:

Struggling with while loop (computer graphics)

Working on a little project to do with computer graphics. So far I have (I think) everything in order as the code below patches my world to the screen fine.
However, I have a final hurdle to jump: I would like the code to patch for different values of theta. In the code, it is set at 2*pi/4 but I would like to iterate and patch for every angle between 0:pi/4:2*pi. However, when I try to put the code in a for or while loop it doesn't seem to do what I expect, that is, to patch with one angle, then patch with another etc.
Really stuck I have tried a lot of stuff and now I'm just without any ideas. Would really appreciate any help or suggestions.
function world()
% Defining House Vertices
house_verts = [-5, 0, -5;
5, 0, -5;
5, 10, -5;
0,15,-5;
-5,10,-5;
-5,0,5;
5,0,5;
5,10,5;
0,15,5;
-5,10,5];
% Sorting out the homeogenous co-ordinates
ones = [1,1,1,1,1,1,1,1,1,1];
ones=transpose(ones);
house_verts = [house_verts, ones];
house_verts = transpose(house_verts);
% House faces
house_faces = [1,2,3,4,5;
2,7,8,3,3;
6,7,8,9,10;
1,6,10,5,5;
3,4,9,8,8;
4,5,10,9,9;
1,2,7,6,6];
world_pos = [];
% creating a street
street_vector = [1,0,1]; % the direction of the street
orthog_street_vector = [-1,0,1];
for i = 1:15
% current_pos1 and 2 will be the positions of the two houses
% opposite each other on the street
current_pos1 = 30*i*street_vector + 50*orthog_street_vector;
current_pos2 = 30*i*street_vector - 50*orthog_street_vector;
world_pos = [world_pos;current_pos1;current_pos2];
end
% initialising world vertices and faces
world_verts = [];
world_faces = [];
% Populating the street
for i =1:size(world_pos,1)
T = transmatrix(world_pos(i,:)); % a translation matrix
s = [1,1/2 + rand(),1];
S=scalmatrix(s); % a matrix for a random scaling of the height (y-coordinate)
Ry = rotymatrix(rand()*2*pi); % a matrix for a random rotation about the y-axis
A = T*Ry*S; % the compound transformation matrix to take the house into the world
obj_faces = size(world_verts,2) + house_faces; %increments the basic house faces to match the current object
obj_verts = A*house_verts;
world_verts = [world_verts, obj_verts]; % adds the vertices to the world
world_faces = [world_faces; obj_faces]; % adds the faces to the world
end
% initialising aligned vertices
align_verts = [];
% Aligning the vertices to the particular camera at angle theta
for elm = world_verts
x = 350 + 350*cos(2*pi/4);
z = 350 + 350*sin(2*pi/4);
y = 80;
u = [x,y,z];
v = [250,0,250];
d = v - u;
phiy = atan2(d(1),d(3));
phix = -atan2(d(2),sqrt(d(1)^2+d(3)^2));
T = transmatrix([-u(1),-u(2),-u(3)]);
Ry = rotymatrix(phiy);
Rx = rotxmatrix(phix);
A = Rx*Ry*T;
align_verts = [align_verts, A*elm];
end
% initialising projected vertices
proj_verts=[];
% Performing the projection
for elm = align_verts
proj = projmatrix(10);
projverts = proj*elm;
projverts = ((10/projverts(3))*projverts);
proj_verts = [proj_verts,projverts];
end
% Displaying the world
for i = 1:size(world_faces,1)
for j = 1:size(world_faces,2)
x(j) =proj_verts(1,world_faces(i,j));
z(j) = proj_verts(2,world_faces(i,j));
end
patch(x,z,'w')
end
end
function T = transmatrix(p)
T = [1 0 0 p(1) ; 0 1 0 p(2) ; 0 0 1 p(3) ; 0 0 0 1];
end
function S = scalmatrix(s)
S = [s(1) 0 0 0 ; 0 s(2) 0 0 ; 0 0 s(3) 0 ; 0 0 0 1];
end
function Ry = rotymatrix(theta)
Ry = [cos(theta), 0, -sin(theta),0;
0,1,0,0;
sin(theta),0,cos(theta),0;
0,0,0,1];
end
function Rx = rotxmatrix(phi)
Rx = [1, 0, 0, 0;
0, cos(phi), -sin(phi), 0;
0, sin(phi), cos(phi), 0;
0, 0, 0, 1];
end
function P = projmatrix(f)
P = [1,0,0,0
0,1,0,0
0,0,1,0
0,0,1/f,0];
end
Updated code: managed to get the loop to work but now there is some bug i don't understand when it does a full rotation again any help would be great.
function world()
% Defining House Vertices
house_verts = [-5, 0, -5;
5, 0, -5;
5, 10, -5;
0,15,-5;
-5,10,-5;
-5,0,5;
5,0,5;
5,10,5;
0,15,5;
-5,10,5];
% Sorting out the homeogenous co-ordinates
ones = [1,1,1,1,1,1,1,1,1,1];
ones=transpose(ones);
house_verts = [house_verts, ones];
house_verts = transpose(house_verts);
% House faces
house_faces = [1,2,3,4,5;
2,7,8,3,3;
6,7,8,9,10;
1,6,10,5,5;
3,4,9,8,8;
4,5,10,9,9;
1,2,7,6,6];
world_pos = [];
% creating a street
street_vector = [1,0,1]; % the direction of the street
orthog_street_vector = [-1,0,1];
for i = 1:15
% current_pos1 and 2 will be the positions of the two houses
% opposite each other on the street
current_pos1 = 30*i*street_vector + 50*orthog_street_vector;
current_pos2 = 30*i*street_vector - 50*orthog_street_vector;
world_pos = [world_pos;current_pos1;current_pos2];
end
% initialising world vertices and faces
world_verts = [];
world_faces = [];
% Populating the street
for i =1:size(world_pos,1)
T = transmatrix(world_pos(i,:)); % a translation matrix
s = [1,1/2 + rand(),1];
S=scalmatrix(s); % a matrix for a random scaling of the height (y-coordinate)
Ry = rotymatrix(rand()*2*pi); % a matrix for a random rotation about the y-axis
A = T*Ry*S; % the compound transformation matrix to take the house into the world
obj_faces = size(world_verts,2) + house_faces; %increments the basic house faces to match the current object
obj_verts = A*house_verts;
world_verts = [world_verts, obj_verts]; % adds the vertices to the world
world_faces = [world_faces; obj_faces]; % adds the faces to the world
end
% initialising aligned vertices
align_verts = [];
% initialising projected vertices
proj_verts=[];
% Aligning the vertices to the particular camera at angle theta
theta = 0;
t = 0;
while t < 100
proj_verts=[];
align_verts = [];
for elm = world_verts
x = 300 + 300*cos(theta);
z = 300 + 300*sin(theta);
y = 80;
u = [x,y,z];
v = [200,0,200];
d = v - u;
phiy = atan2(d(1),d(3));
phix = -atan2(d(2),sqrt(d(1)^2+d(3)^2));
T = transmatrix([-u(1),-u(2),-u(3)]);
Ry = rotymatrix(phiy);
Rx = rotxmatrix(phix);
A = Rx*Ry*T;
align_verts = [align_verts, A*elm];
end
% Performing the projection
for elm = align_verts
proj = projmatrix(6);
projverts = proj*elm;
projverts = ((6/projverts(3))*projverts);
proj_verts = [proj_verts,projverts];
end
% Displaying the world
for i = 1:size(world_faces,1)
for j = 1:size(world_faces,2)
x(j) = proj_verts(1,world_faces(i,j));
z(j) = proj_verts(2,world_faces(i,j));
end
patch(x,z,'w')
pbaspect([1,1,1]); % adjusts the aspect ratio of the figure
end
title('Projected Space', 'fontsize', 16, 'interpreter', 'latex')
xlabel('$x$', 'fontsize', 16, 'interpreter', 'latex')
ylabel('$z$', 'fontsize', 16, 'interpreter', 'latex')
zlabel('$y$', 'fontsize', 16, 'interpreter', 'latex')
axis([-5,5,-5,2,0,5]) % sets the axes limits
view(0,89)
pause(0.0000001)
theta = theta + 0.01;
clf
end
end
function T = transmatrix(p)
T = [1 0 0 p(1) ; 0 1 0 p(2) ; 0 0 1 p(3) ; 0 0 0 1];
end
function S = scalmatrix(s)
S = [s(1) 0 0 0 ; 0 s(2) 0 0 ; 0 0 s(3) 0 ; 0 0 0 1];
end
function Ry = rotymatrix(theta)
Ry = [cos(theta), 0, -sin(theta),0;
0,1,0,0;
sin(theta),0,cos(theta),0;
0,0,0,1];
end
function Rx = rotxmatrix(phi)
Rx = [1, 0, 0, 0;
0, cos(phi), -sin(phi), 0;
0, sin(phi), cos(phi), 0;
0, 0, 0, 1];
end
function P = projmatrix(f)
P = [1,0,0,0
0,1,0,0
0,0,1,0
0,0,1/f,0];
end

plotting optical flow in matlab using vision tool box

I am trying to plot optical flow using quiver. I can plot the optical flow lines but not the arrows. This code is similar examples on Matlab tutorials.
Following is the code
function display_optical_flow (video_file_name)
vid_reader_obj = vision.VideoFileReader(video_file_name, 'VideoOutputDataType','single');
optical_flow_calculator = vision.OpticalFlow('Method','Lucas- Kanade','TemporalGradientFilter','Derivative of Gaussian', 'MotionVectorImageOutputPort', ...
true, 'OutputValue', 'Horizontal and vertical components in complex form', 'NoiseReductionThreshold',0.02);
screen_size = get(0, 'ScreenSize');
player_window_pos = [20 screen_size(4)-300 400 400];
video_display_originalVideo = vision.VideoPlayer('Name', 'Original Input Video', 'Position', player_window_pos);
player_window_pos(1) = player_window_pos(1) + 500;
video_display_opticalFlow = vision.VideoPlayer('Name','Optical Flow Vector', 'Position',player_window_pos);
player_window_pos(1) = player_window_pos(1) + 500;
video_display_of_image = vision.VideoPlayer('Name','Optical Flow image', 'Position',player_window_pos);
shape_inserter_line = vision.ShapeInserter('Shape','Lines', 'BorderColor','Custom','CustomBorderColor', [255 255 0]);
motion_vector_gain=20;
decimFactorRow = 5;
decimFactorCol = 5;
borderOffset = 5;
flag_first_time = true;
while ~isDone(vid_reader_obj)
cur_rgb_frame = step(vid_reader_obj);
cur_gray_frame = rgb2gray(cur_rgb_frame);
[optical_flow_vector IMV]= step(optical_flow_calculator, cur_gray_frame);
%magnitude of optical flow vectors by dot product
%of_magnitude= optical_flow_vector .* conj(optical_flow_vector);
if true == flag_first_time
flag_first_time = false;
[row col] = size(optical_flow_vector);
rowV = borderOffset:decimFactorRow:(row-borderOffset);
colV = borderOffset:decimFactorCol:(col-borderOffset);
[Y X] = meshgrid(rowV, colV);
end
lines =videooptflowlines(optical_flow_vector, 20);
if ~isempty(lines)
motion_vectors = step(shape_inserter_line, cur_rgb_frame, lines);
step(video_display_opticalFlow, motion_vectors);
end
%Display
step(video_display_originalVideo, cur_rgb_frame);
step(video_display_of_image, IMV);
%
[Xsize Ysize] = meshgrid(1:size(cur_gray_frame, 2), 1:size(cur_gray_frame, 1));
imshow(cur_gray_frame); hold on;
Real_part = real(optical_flow_vector(:));
Imag_part = imag(optical_flow_vector(:));
quiver(Xsize(:), Ysize(:), Real_part(:), Imag_part(:), 0);
pause;
end
release (video_display_opticalFlow);
release (video_display_originalVideo);
release (vid_reader_obj);
This do not show the arrow as I expect to see on each frame image by quiver.
What wrong I should do to correct the code?
nitin