dedbi reverse the words that is, ‘a’ will be replaced by ‘z’, ‘b’ will be replaced by ‘y’, ‘c’ will be replaced by ‘x’ and so on. dedbi will do the same for capital letter t
Pseudo code:
function out = func_name(in)
in = array of ascii values from original in values (can be done with one command)
out = vector if zeros the size of in (one command)
loop through all numbers of in
ch = current char ascii value (just because it is easier to write ch than in(index) in my opinion)
if ch is btw 65 and 96
subtract 65 so ch is 1-26
find 26-ch (invert)
add 65 so ch is 65-96
if ch is btw 97 and 122
do the same as above with adjusted numbers
end if
out(index_of_for_loop) = ch
end loop
end function
Note: In general, it is best to avoid code that has many copy-paste section because it can be difficult to edit quickly.
One approach -
%// in_str: Input string
%// Logical masks for upper and lower case letters
upper_mask = in_str>=65 & in_str<=90 %// OR isstrprop(in_str,'upper')
lower_mask = in_str>=97 & in_str<=122 %// OR isstrprop(in_str,'lower')
%// Initialize output string
out_str = in_str
%// Replace upper letters with "flipped" upper letters; repeat for small letters
out_str(upper_mask) = char(in_str(upper_mask) + 2*(78-in_str(upper_mask))-1)
out_str(lower_mask) = char(in_str(lower_mask) + 2*(110-in_str(lower_mask))-1)
Those numbers: 78
and 110
act as the "middle numbers" for the capital and small letters ranges respectively and are used for finding differences for each letter in those two categories.
Sample run -
>> in_str,out_str
in_str =
adzC+*6AY&‘///\?abAB
out_str =
zwaX+*6ZB&‘///\?zyZY
I just posted the solution, than I realised that I probably shouldn't solve your assignment. Anyways, here are a couple of tips for you:
You can use the function fliplr()
to invert the elements in a (row) vector. (hint: reverse the alphabet)
If you do: [~, index] = ismember('abcd','ac')
, than index
will be: index=[1 3]
(hint: the index of 'a' and c
in the alphabet are the same as for z
and 'y' in the reverse alphabet)
Here's a way to do that:
alphabet = 'abcdefghijklmopqrstuvwxyz';
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
ralphabet = fliplr(alphabet);
RALPHABET = fliplr(ALPHABET);
txt = 'abc d ?!.< n AC';
[~, index] = ismember(txt,alphabet);
target = index ~= 0;
src = index(target);
[~, INDEX] = ismember(txt,ALPHABET);
TARGET = INDEX ~= 0;
SRC = INDEX(TARGET);
txtInvert = txt;
txtInvert(target) = ralphabet(src);
txtInvert(TARGET) = RALPHABET(SRC);
Output:
zyx w ?!.< n ZX
Another solution:
function xtx = dedbi(xtx)
xtx(xtx >= 'a' & xtx <= 'z') = 219 - xtx(xtx >= 'a' & xtx <= 'z');
xtx(xtx >= 'A' & xtx <= 'Z') = 155 - xtx(xtx >= 'A' & xtx <= 'Z');
end