Info

This question is closed. Reopen it to edit or answer.

I feel like my code is too long for what it tries to do, how can I make it shorter?

1 view (last 30 days)
I feell like my code is too long for what it is trying to do... I wrote a function that calculates a sigmoid function which is fine... with this code:
% code
function [ yValues ] = sigmaFunc( data,a,b )
%sigmaFunc calculates the sigmoid function y=a/(1+exp(-bx))
% data = data vector
% a = value for the 'a' coefficient
% b = value for the 'b' coefficient
yValues = zeros(size(data,1),size(data,2));
for ii = 1:length(data)
yValues(ii) = a/(1+exp(-b.*data(ii)));
end
and then I was requested to write a function with no input/output data that calculates 3 sigmoid functions with same a&b but with different x-data - I thought that using a loop in this case is not so efficient, but now I feel like my code is too long - can you think about ways to do the same with less lines? since I cannot think of anything :(
% code
a=4;
b = 0.5;
xDatai=-50:0.5:50;
%using sigmaFunc to receive my values vector
[ yValues ] = sigmaFunc( xDatai,a,b );
%devide the image into 3 graphs arranged in a column
%and put yValues in the 1st place.
subplot(3,1,1);
%plot yValues with black line
plot(yValues,'k');
%define x axis title
xlabel('1st x data');
%define y axis title
ylabel('1st y results');
%define graph title
title('Sigmoid Graph - increment =0.5')
%define y axis limits
ylim([0 6]);
%the same as before (xDatai) is done for xDataii
xDataii = -50:5:50;
[ yValuesi ] = sigmaFunc( xDataii,a,b );
subplot (3,1,2);
plot(yValuesi,'k');
xlabel('2nd x');
ylabel('2nd y results');
title('Sigmoid Graph - increment =5');
ylim([0 6]);
%the same as before (xDatai) is done for xDataiii
xDataiii= -50:10:50;
[ yValuesii ] = sigmaFunc( xDataiii,a,b );
subplot(3,1,3);
plot(yValuesii,'k');
xlabel('3rd x');
ylabel('3rd y results');
title('Sigmoid Graph - increment =10');
ylim([0 6])
end

Answers (1)

sixwwwwww
sixwwwwww on 6 Dec 2013
you can reduce it as follow:
function YourFunctionName
a = 4;
b = 0.5;
StepSize = [0.5, 5, 10];
for x = 1:numel(StepSize)
xDatai = -50:0.5:50;
yValues = sigmaFunc(xDatai, a, b);
subplot(3, 1, x),
plot(yValues,'k'),
xlabel('1st x data'),
ylabel('1st y results'),
title(strcat('Sigmoid Graph - increment =', num2str(StepSize(x)))),
ylim([0 6]),
end
function [ yValues ] = sigmaFunc( data,a,b )
ii = 1:length(data);
yValues = a./(1+exp(-b*data(ii)));

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!