hello friends, see I am executing a simple code . I want your little help in it.

1 次查看(过去 30 天)
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.

回答(2 个)

Geoff Hayes
Geoff Hayes 2015-4-7
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!

Radha Krishna Maddukuri
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.

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by