create a caesar cipher in matlab

Here is a simple implementation of Caesar cipher encryption in MATLAB:

main.m
function cipher_text = caesar_cipher(plain_text, shift)
    % Convert plain text to uppercase
    plain_text = upper(plain_text);
  
    % Initialize cipher text
    cipher_text = '';
    
    % Iterate over each character in the plain text
    for i=1:length(plain_text)
        % Get the ASCII code of the current character
        char_code = uint8(plain_text(i));
        
        % Shift the character code by the specified shift amount
        shifted_code = char_code + shift;
        
        % Wrap around if the shifted code goes beyond 'Z' or 'A' (for uppercase alphabet)
        if shifted_code > 90
            shifted_code = shifted_code - 26;
        elseif shifted_code < 65
            shifted_code = shifted_code + 26;
        end
        
        % Convert the shifted character code back to a character and append it to the cipher text
        cipher_text = [cipher_text, char(shifted_code)];
    end
end
925 chars
27 lines

The caesar_cipher function takes two inputs - the plain text message and the shift amount. It then converts the plain text to uppercase, initializes an empty string for the cipher text, and iterates over each character in the plain text. For each character, it gets its ASCII code, applies the shift by adding the shift amount, handles wrapping around if necessary, converts the shifted code back to a character, and appends it to the cipher text. The function returns the cipher text.

Note that this implementation only works with uppercase letters, and does not handle non-alphabetic characters. These limitations can be addressed with some modifications to the code.

related categories

gistlibby LogSnag