Using while loops to approximate the taylor series of acsc - matlab

I'm trying to approximate acsc using a while loop without much success, currently, the compiler is giving me the error that 'Array indices must be positive integers or logical values.' With an error at line 9. Any help is appreciated.
acsc_appr2 = [];
for j = 1:length(x_array)
x = x_array(j);
i = 1;
k(1) = 0;
acsc_appr2 (1) =inf;
while acsc_appr2 (i) >= 1e-6
acsc_appr2 (i) = acsc_appr2 (i-1) + ...
(factorial(2*k)/((2^(2*k)*factorial(k)^2)))*...
(1./((2*k+1)*(x.^(2*k+1))));
k = k+1;
i = i+1;
end
end
figure(1);
plot(x_array, acsc(x_array),'-k', 'LineWidth', 2);
hold on
plot(x_array, acsc_appr2,'--r');
hold off
xlabel('x'), ylabel('y');
legend('acsc','acsc approximation', 'location', 'northeast');
title('Q4b id:30012521');
set(gcf,'Position', get(gcf,'Position') + [0,0,150,0]);
pos1 = get(gcf,'Position');
set(gcf,'Position', pos1 - [pos1(3)/2,0,0,0]);```

Related

Unable to perform assignment because the left and right sides have a different number of elements. MATLAB ERROR

I try to compute a few matrices using MATLAB. After run this code I get a error "Unable to perform assignment because the left and right sides have a different number of elements."
After simple debugging i get conclusion that after comment X(j) and Y(j) program run correctly.
I looked on some similar problem but I cannot find sth that can help me with above problem
clear all
close all
clc
%stale
a1 = 1;
a2 = 1;
a3 = 1;
a4 = 1;
a5 = 1;
%% Napęd 2
X=0; Y=0; Z=0;
th1 = 0; th2 = 0; th3 = 0; th4 = 0; th5 = 0;
%alfa2 = 1;
alfa2 = 0:(pi/12):(pi);
alfa1 = 0; alfa3 = 0; alfa4 = 0; alfa5 = 0;
d5=1; d4=1; d3=1; d2=1; d1=1;
a3 = 1;
a3 = 0.1:(1/14):1;
for j = 1 : length(alfa2)
X(j) = a5*cos(th1)*cos(th4)*cos(th5) + a5*sin(th1)*sin(alfa2(j))*sin(th4)*cos(th5) - a5*cos(th1)*sin(th4)*sin(th5) + a5*sin(th1)*sin(alfa2(j))*cos(th4)*sin(th5) + d4*sin(th1)*cos(alfa2(j)) + a3*cos(th1) + alfa2*cos(th1);
Y(j) = a5*sin(th1)*sin(th4)*cos(th5) - a5*cos(th1)*sin(alfa2(j))*cos(th4)*cos(th5) - a5*sin(th1)*sin(th4)*sin(th5) - a5*cos(th1)*sin(alfa2(j))*cos(th4)*sin(th5) + d4*sin(th1)*cos(alfa2(j)) + a3*cos(th1) + alfa2*cos(th1);
Z(j) = a5*cos(alfa2(j))*sin(th4)*cos(th5) + a5*cos(alfa2(j))*cos(th4)*sin(th5) -d4*sin(alfa2(j)) + d1;
end
figure(1);
subplot(2, 2, 1); plot3(Y, X, Z); grid on; title("Przestrzen XYZ");
xlabel('y'); ylabel('X'); zlabel('Z')
subplot(2, 2, 2); plot(Y, X); grid on; xlabel('Y'); ylabel('X');
title("Plaszczyzna XY");
subplot(2, 2, 3); plot(X, Z); grid on; xlabel('X'); ylabel('Z');
title("Plaszczyzna XZ");
subplot(2, 2, 4); plot(Y, Z); grid on; xlabel('Y'); ylabel('Z');
title("Plaszczyzna YZ");
This is my workspace:
Workspace
You are using alpha2 in the end of your equations, which is a vector. You likely want alpha2(j)

All my weights for gradient descent become 0 on feature expansion

I have 2 features which I expand to contain all possible combinations of the two features under order 6. When I do MATLAB's fminunc, it returns a weight vector where all elements are 0.
The dataset is here
clear all;
clc;
data = load("P2-data1.txt");
m = length(data);
para = 0; % regularization parameter
%% Augment Feature
y = data(:,3);
new_data = newfeature(data(:,1), data(:,2), 3);
[~, n] = size(new_data);
betas1 = zeros(n,1); % initial weights
options = optimset('GradObj', 'on', 'MaxIter', 400);
[beta_new, cost] = fminunc(#(t)(regucostfunction(t, new_data, y, para)), betas1, options);
fprintf('Cost at theta found by fminunc: %f\n', cost);
fprintf('theta: \n');
fprintf(' %f \n', beta_new); % get all 0 here
% Compute accuracy on our training set
p_new = predict(beta_new, new_data);
fprintf('Train Accuracy after feature augmentation: %f\n', mean(double(p_new == y)) * 100);
fprintf('\n');
%% the functions are defined below
function g = sigmoid(z) % running properly
g = zeros(size(z));
g=ones(size(z))./(ones(size(z))+exp(-z));
end
function [J,grad] = regucostfunction(theta,x,y,para) % CalculateCost(x1,betas1,y);
m = length(y); % number of training examples
J = 0;
grad = zeros(size(theta));
hyp = sigmoid(x*theta);
err = (hyp - y)';
grad = (1/m)*(err)*x;
sum = 0;
for k = 2:length(theta)
sum = sum+theta(k)^2;
end
J = (1/m)*((-y' * log(hyp) - (1 - y)' * log(1 - hyp)) + para*(sum) );
end
function p = predict(theta, X)
m = size(X, 1); % Number of training examples
p = zeros(m, 1);
index = find(sigmoid(theta'*X') >= 0.5);
p(index,1) = 1;
end
function out = newfeature(X1, X2, degree)
out = ones(size(X1(:,1)));
for i = 1:degree
for j = 0:i
out(:, end+1) = (X1.^(i-j)).*(X2.^j);
end
end
end
data contains 2 columns of rows followed by a third column of 0/1 values.
The functions used are: newfeature returns the expanded features and regucostfunction computes the cost. When I did the same approach with the default features, it worked and I think the problem here has to do with some coding issue.

Plotting In MATLAB

I have a code that I would like to add an additional plot inside. I want to plot the relative error of two of my functions. I am unsure where in the loop to place this so that it doesn't give me an error message and plots all three cases as single graphs. Also, my relative error code may have some mistakes, which is what may be causing the problem.
This is the relative error code:
rel_error = (y_exact1 - Y(:,2)')./y_exact; %relative error
figure()
plot(T,rel_error,'r')
This is the function I need to add it into
function ivp1()
clear;clc;close all;
t=linspace(0,2.5);
K=[.02 .1 1.5];
for i=1:3
k =K(i);
[T,Y] = ode45(#prblm1_fun,t,0); %Solving for the approximate solution to the IVP
figure()
plot(T,Y)
hold on
y_exact1 = 1/(k^2+pi^2)*(pi*exp(k*t)-pi*cos(pi*t)-k*sin(pi*t));
y_exact2 = 1/(2*k)*(exp(k*(t-1))-1) + pi/(k^2+pi^2)*(exp(k*t) + exp(k* (t-1)));
y_exact3 = 1/2/k*(exp(k*(t-1))-exp(k*(t-2))) + pi/(k^2+pi^2)*(exp(k*t) + exp(k*(t-1))) + 1/2/(k-1)*(exp(k*(t-2)) - exp(t-2));
for i=1:length(t)
if t(i)<1
plot(t(i),y_exact1(i),'mo')
hold on
elseif t(i)<2
plot(t(i),y_exact2(i),'mo')
hold on
else
plot (t(i),y_exact3(i),'mo')
hold on
end
end
end
function dy= prblm1_fun(t,y) %This is the function of the IVP for varying values of t
dy = zeros(1,1);
if t < 1
dy(1)= y(1)*k + sin(pi*t);
elseif t < 2
dy(1)= y(1)*k + 0.5;
else
dy(1)= y(1)*k + exp(t-2)/2;
end
end
end
This is the desired result for one of the k values:
Two erroneous places:
1) Y is a 100x1 matrix from the result of ode45. Trying to access Y(:,2) leads into a out-of-boundary error.
2) y_exact is not defined. You only have y_exact1, y_exact2 and y_exact3.
Sample code:
function ivp1()
clear;clc;close all;
t=linspace(0,2.5);
K=[.02 .1 1.5];
for i=1:3
k =K(i);
[T,Y] = ode45(#prblm1_fun,t,0); %Solving for the approximate solution to the IVP
figure()
plot(T,Y)
hold on
y_exact1 = 1/(k^2+pi^2)*(pi*exp(k*t)-pi*cos(pi*t)-k*sin(pi*t));
y_exact2 = 1/(2*k)*(exp(k*(t-1))-1) + pi/(k^2+pi^2)*(exp(k*t) + exp(k* (t-1)));
y_exact3 = 1/2/k*(exp(k*(t-1))-exp(k*(t-2))) + pi/(k^2+pi^2)*(exp(k*t) + exp(k*(t-1))) + 1/2/(k-1)*(exp(k*(t-2)) - exp(t-2));
for j=1:length(t)
if t(j)<1
y_exact = y_exact1(j);
elseif t(j)<2
y_exact = y_exact2(j);
else
y_exact = y_exact3(j);
end
plot(t(j),y_exact,'mo')
end
rel_error = (y_exact1 - Y(:,1)')./y_exact; %relative error
plot(T,rel_error,'r')
end
function dy= prblm1_fun(t,y) %This is the function of the IVP for varying values of t
dy = zeros(1,1);
if t < 1
dy(1)= y(1)*k + sin(pi*t);
elseif t < 2
dy(1)= y(1)*k + 0.5;
else
dy(1)= y(1)*k + exp(t-2)/2;
end
end
end
Sample output:

how to count foreground segmented faces in image?

i have applied foreground segmentation on an image.its now showing the white areas instead of those faces in original image.now i want to counnt those faces how to do it?? output image is attached.......................................................
close all;
clear all;
clc;
rgbInputImage = imread('Crowd-of-people-008.jpg');
labInputImage = applycform(rgbInputImage,makecform('srgb2lab'));
Lbpdfhe = fcnBPDFHE(labInputImage(:,:,1));
labOutputImage = cat(3,Lbpdfhe,labInputImage(:,:,2),labInputImage(:,:,3));
rgbOutputImage = applycform(labOutputImage,makecform('lab2srgb'));
figure, imshow(rgbInputImage);
figure, imshow(rgbOutputImage);
img=rgbOutputImage;
final_image = zeros(size(img,1), size(img,2));
if(size(img, 3) > 1)
for i = 1:size(img,1)
for j = 1:size(img,2)
R = img(i,j,1);
G = img(i,j,2);
B = img(i,j,3);
if(R > 92 && G > 40 && B > 20)
v = [R,G,B];
if((max(v) - min(v)) > 15)
if(abs(R-G) > 15 && R > G && R > B)
final_image(i,j) = 1;
end
end
end
end
end
end
binaryImage=im2bw(final_image,0.6);
figure, imshow(binaryImage);
binaryImage = imfill(binaryImage, 'holes');
figure, imshow(binaryImage);
%binaryImage = bwareaopen(binaryImage,1890);
%figure,imshow(binaryImage);
%labeledImage = bwlabel(binaryImage, 8);
%blobMeasurements = regionprops(labeledImage, final_image, 'all');
%numberOfPeople = size(blobMeasurements, 1);
%imagesc(rgbInputImage); title('Outlines, from bwboundaries()');
%hold on;
%boundaries = bwboundaries(binaryImage);
%for k = 1 : numberOfPeople
%thisBoundary = boundaries{k};
%plot(thisBoundary(:,2), thisBoundary(:,1), 'g', 'LineWidth', 2);
%end
%imagesc(rgbInputImage);
%hold on;
%title('Original with bounding boxes');
%for k = 1 : numberOfPeople
%thisBlobsBox = blobMeasurements(k).BoundingBox;
%x1 = thisBlobsBox(1);
%y1 = thisBlobsBox(2);
%x2 = x1 + thisBlobsBox(3);
%y2 = y1 + thisBlobsBox(4);
%x = [x1 x2 x2 x1 x1];
%y = [y1 y1 y2 y2 y1];
%plot(x, y, 'LineWidth', 2);
%end
binaryimage = bwboundaries(binaryimage);
imshow(binaryimage)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(Binaryimage))))
hold on
for k = 1:length(Binaryimage)
boundary = Binaryimage{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
endB = bwboundaries(binaryimage);
imshow(binaryimage)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(Binaryimage))))
hold on
end
for k = 1:length(B)
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
end
Use [L, num] = bwlabel(BW, n) to compute num, the number of connected components. See here.
You can use vision.CascadeObjectDetector in the Computer Vision System Toolbox to detect faces without background subtraction.

Changing the order in for-loop

I have a matrix (with the size of A and B; suppose 100x100) and want to fill in with smaller matrix (or block) with the size of a and b (suppose 12x12).
As it is clear, the loop starts from "j" and then goes to the next row. Actually I want to use the same loop, by adding another variable to impose that it first complete the columns. Any idea that how I should define this new variable in the following loop to control the completion direction.
M = zeros(100,100);
for j = 1:12:100-12+1
for i = 1:12:100-12+1
block = rand(12,12);
M(i:i+11, j:j+11) = block;
imagesc(M); axis equal tight xy
pause(.1)
end;
end;
Why not just do
M = zeros(100,100);
for j = 1:12:100-12+1
for i = 1:12:100-12+1
block = rand(12,12);
M(i:i+11, j:j+11) = block;
imagesc(M); axis equal tight xy
pause(.1)
end;
end;
Now you will iterate over the i's first.
Incidentally, I recommend not using i and j as loop variables - they shadow the built in sqrt(-1) imaginary number...
update based on your comment, it seems you want to leave the order of i and j in the outer loop, and add "another parameter" to change the direction. The following code does all that. Is this what you are after?
M = zeros(100,100);
rowFirst = true; % set to false for "column first"
for i = 1:12:100-12+1
for j = 1:12:100-12+1
block = rand(12,12);
if rowFirst
M((0:11) + i, (0:11) + j) = block;
else
M((0:11) + j, (0:11) + i) = block;
end
imagesc(M); axis equal tight xy
pause(.1)
end
end
update 2 and now "even for non square matrix" (not tested, late at night):
M = zeros(100, 120);
rowFirst = true;
sz = size(M);
blockSize = 12;
v = 1:blockSize;
nrc = floor(sz / blockSize);
if rowFirst
nrc = reverse(nrc);
end
for ii = blockSize * (0:nrc(1)-1)
for jj = blockSize * (0:nrc(2)-1)
block = rand(blockSize*[1 1]);
if ~rowFirst
block = block';
end if
M(v + ii, v+jj) = block;
if rowFirst
imagesc(M);
else
imagesc(M');
end
axis equal tight xy
pause(0.1)
end
end
LAST TIME if you insist that the outer loop iterates over j and the inner loop over i, yet that in some instances j is the "faster moving" variable, you can do the following.
P = 120;
Q = 180;
M = zeros(P, Q); % not a square matrix
rowFirst = true; % a switch you can flip
blockSize = 15; % size of block
sz = floor(size(M)/blockSize); % number of iterations in j, i
nr = sz(1); nc = sz(2);
vv = 1:blockSize;
for jj = 0: (nc-1)
for ii = 0: (nr-1)
if(rowFirst)
kk = ii * blockSize;
ll = jj * blockSize;
else
nn = jj * nr + ii;
ll = mod(nn, nc);
kk = floor(nn / nc);
%ll = (nn - kk * nc);
fprintf(1, 'ii, jj, nn = [%d, %d, %d]: [kk, ll] = %d, %d\n', ii, jj, nn, kk, ll)
ll = ll * blockSize; kk = kk * blockSize;
% mod(nn, P);
end
M(kk+vv, ll+vv) = rand(blockSize*[1 1]);
imagesc(M);
axis tight equal xy;
pause(0.1);
end
end