Function in Separate File

65 次查看(过去 30 天)
Hi all. I need to convert this encryption program into 2 separate functions, one for encryption, and one for decryption. I am confused at the moment. The code below is the current code with everything in one file. How would I create 2 separate functions for the encryption and decryption? Thanks
clear
clc
%Prompts for user input
message = input('Enter a message to encode: ', 's');
encryption = message;
%Sets the terms and conditions for encoding characters, and if else then
%mapping them to themselves
for i = 1:length(encryption)
x = encryption(i);
if x >= 'A' && x <= 'Z'
if x >= 'U'
x = x - 20;
else
x = x + 6;
end
elseif x>= 'a' && x <= 'z'
if x >= 'u'
x = x - 20;
else
x = x + 6;
end
end
encryption(i) = x;
end
%Same thing as above except dealing with the decryption, mapping to
%themselves if necessary.
decryption = encryption;
for i = 1:length(decryption)
x = decryption(i);
if x >= 'A' && x <= 'Z'
if x <= 'F'
x = x + 20;
else
x = x - 6;
end
elseif x>= 'a' && x <= 'z'
if x <= 'f'
x = x + 20;
else
x = x - 6;
end
end
decryption(i) = x;
end
%Prints the output
fprintf("\nMessage: %s\n\n", message);
fprintf("Encrypted: %s\n\n", encryption);
fprintf("Decrypted: %s\n\n", decryption);

采纳的回答

KALYAN ACHARJYA
KALYAN ACHARJYA 2019-4-25
编辑:KALYAN ACHARJYA 2019-4-25
Main Script:
clear;
clc; close all;
%% Message Input
message=input('Enter a message to encode: ', 's');
encryption_message=message;
%To call encryption function
en=encryption_fun(encryption_message);
%% To call decryption function
dn=decryption_fun(en);
%% Prints the output
fprintf('\nMessage: %s\n\n',message);
fprintf('Encrypted: %s\n\n',en);
fprintf('Decrypted: %s\n\n',dn);
Save the encryption function in differnt file (Must be in current directory, save file name as encryption_fun.m)
function encryption=encryption_fun(encryption)
%Sets the terms and conditions for encoding characters, and if else then
%mapping them to themselves
for i=1:length(encryption)
x=encryption(i);
if x >= 'A' && x <= 'Z'
if x >= 'U'
x = x - 20;
else
x = x + 6;
end
elseif x>= 'a' && x <= 'z'
if x >= 'u'
x = x - 20;
else
x = x + 6;
end
end
encryption(i) = x;
end
end
Save the decryption function in differnt file (Must be in current directory, save file name as decryption_fun.m)
function decryption=decryption_fun(encryption)
decryption=encryption;
for i=1:length(decryption)
x = decryption(i);
if x >= 'A' && x <= 'Z'
if x <= 'F'
x = x + 20;
else
x = x - 6;
end
elseif x>= 'a' && x <= 'z'
if x <= 'f'
x = x + 20;
else
x = x - 6;
end
end
decryption(i) = x;
end
end
Now run the main code (First one) and results:
Enter a message to encode: Kalyan
Message: Kalyan
Encrypted: Qgregt
Decrypted: Kalyan

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by