Using char to convert a numerical array into string

2 views (last 30 days)
Hi everyone, I'm new on Matlab and I'm practicing.. I have a problem using char to convert an ASCII array into a string. I post you my code to better understand what is my problem:
s1='STRING'; %new string
n=length(s1); %length of string
k=3; %k number
char=zeros(1,n);
char_ASCII=zeros(1,n);
newascii=zeros(1,n);
for i=1:n
char(i)=s1(i);
char_ASCII(i)=double(char(i)); %from string to numeric array with double
if ( char_ASCII(i)==32) %if blank space don't do anything
newascii(i)=32;
else
newascii(i)=char_ASCII(i)+k; %otherwise add +k to all cell of array
end
end
Now, I've to use CHAR on my array 'newascii' to get back my modified string, but if I try to do that it returns me an error "Index exceeds matrix dimensions." I've read the help of char but I can't understand where is the error. Hope you can help me, Thank you so much!

Accepted Answer

Walter Roberson
Walter Roberson on 3 Oct 2015
You named your variable "char", which is the same name as the MATLAB routine "char" that you are attempting to invoke to change your numeric values back into characters. When you name a variable the same name as a MATLAB routine, MATLAB cannot tell when you intend to reference the variable and when you intend to reference the routine.
  1 Comment
S LB
S LB on 3 Oct 2015
Oh yes, it's true! I didn't think about that. So stupid thing. Thank you!!

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings 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!