My shifting algorithm does not work at all cases. Could someone please give me feedback what's wrong at my code?

1 view (last 30 days)
This is my task to solve:
And this is my code:
function coded = caesar(char_vect, shift)
shift_max = 126-32;
char_num = numel(char_vect);
shift = shift_max * (shift/shift_max - round(shift/shift_max));
for ii = 1:char_num
if (double(char_vect(ii)) + shift) < 32
sub = double(char_vect(ii)) + shift - 32 + 1;
char_vect(ii) = 126 + sub;
elseif (double(char_vect(ii)) + shift) > 126
add = double(char_vect(ii)) + shift - 126 - 1;
char_vect(ii) = 32 + add;
% char_vect(ii)
char_vect(ii) = double(char_vect(ii)) + shift;
% char_vect(ii)
coded = num2str(char_vect);

Accepted Answer

Maik on 5 Oct 2022
I found my own mistake - thank you again @Walter Roberson!

More Answers (1)

Walter Roberson
Walter Roberson on 5 Oct 2022
Edited: Walter Roberson on 5 Oct 2022
shift = shift_max * (shift/shift_max - round(shift/shift_max));
shift_max is not a power of 2. When you divide by something that is not a power of 2 and then multiply by the same value then you do not generally get back exactly the same value.
The situation is similar to saying that you are working with four decimal places and calculating 3 * (1/3). But to four decimal places 1/3 is 0.3333 and multiply that by 3 you get 0.9999 not the original 1. You can see that if you used 400 decimal places you would have the same issue of not getting back the original number. It is a problem that happens with every fixed numeric base with every finite number of digits in the representation; you do not get away from it until you use an infinite number of positions.
So... don't do that. take your expression
shift_max * (shift/shift_max - round(shift/shift_max));
and expand it:
shift_max * shift / shift_max - shift_max * round(shift/shift_max)
now cancel the numerator and denominator
shift - shift_max * round(shift/shift_max)
and now you are only dealing with integers other than inside the round()
  1 Comment
Maik on 5 Oct 2022
Thank you Walter!
It helped a least to fix the roundig bug.
But it doesn't work properly if I call the function like this:
caesar('x = mean(1:90) + sum(rand(1,23)');',81)
My mentor said, there are some decision mistakes I made.
However, I used Excel to calculate it manually - it worked. So, I still could'nt get the mistake.

Sign in to comment.


Find more on Loops and Conditional Statements in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by