hello friends, see I am executing a simple code . I want your little help in it.
1 view (last 30 days)
Show older comments
close all;
clear all;
clc;
str=('ttttttPttttPPttt');
estring(str)
-----------------------------------------function estring--------------------------------
function estring(str)
len = numel(str);
i = 0;
count = zeros(1,len);
while( i<len )
j=0;
count(i+1) = 1;
while( true )
j = j + 1;
if( i+j+1 > len )
break;
end
if( str(i+j+1)==str(i+1) )
count(i+1) = count(i+1) + 1;
else
break;
end
end
if( count(i+1)==1 )
a=str(i+1);
length(a);
fprintf('%c',a);
i = i + 1;
else
a=str(i+1);
b=count(i+1);
fprintf('%c%d',a,b);
i = i + b;
end
end
fprintf('\n');
end
this is giving output as t6Pt4P2t3. *I want estring to return the output to script. e.g
y=estring(str) in the script
function a=estring(str)
It is not working. Please suggest me how to do this.
0 Comments
Answers (2)
Geoff Hayes
on 7 Apr 2015
Tina - if you want your function to return a string (rather than writing it to the Command Window with fprintf) the first thing you have to do is change your function signature to return an output value
function [estr] = estring(str)
% initialize estr
estr = '';
Now replace all of your fprintf calls with code that will concatenate the estr with the new data. For example,
fprintf('%c',a);
becomes
estr = [estr a];
and
fprintf('%c%d',a,b);
becomes
estr = [estr a num2str(b)];
Try implementing the above and see what happens!
0 Comments
Radha Krishna Maddukuri
on 7 Apr 2015
Hello Tina,
In the function that you have written, you are printing out values, rather you have to assign it to a variable. I have changed your code a bit:
function y = estring(str)
len = numel(str);
i = 0;
count = zeros(1,len);
y=[];
while( i<len )
j=0;
count(i+1) = 1;
while( true )
j = j + 1;
if( i+j+1 > len )
break;
end
if( str(i+j+1)==str(i+1) )
count(i+1) = count(i+1) + 1;
else
break;
end
end
if( count(i+1)==1 )
a=str(i+1);
length(a);
y = [y a];
i = i + 1;
else
a=str(i+1);
b=count(i+1);
y =[y a num2str(b)];
i = i + b;
end
end
end
From this function, when you execute the following command:
>> y = estring(str)
It will work.
0 Comments
See Also
Categories
Find more on String Parsing 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!