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)));
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
b = 0.5;
%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.
%plot yValues with black line
%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);
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 );
xlabel('3rd x');
ylabel('3rd y results');
title('Sigmoid Graph - increment =10');
ylim([0 6])

Answers (1)

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),
xlabel('1st x data'),
ylabel('1st y results'),
title(strcat('Sigmoid Graph - increment =', num2str(StepSize(x)))),
ylim([0 6]),
function [ yValues ] = sigmaFunc( data,a,b )
ii = 1:length(data);
yValues = a./(1+exp(-b*data(ii)));

Community Treasure Hunt

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

Start Hunting!

Translated by