Question for coding Mid-square method in Mathlab
显示 更早的评论
Can somebody please help me to understand this following code?
I don't understand the line 9&10,
s=size(temp);
st=(s(1,2)/2);.
Also, what I am trying to do is to take 4-digits in the middle of 8-digits squared Seed number (i.e.
seed=7182^2 = 51587124 -> 5811 -> 5811^2 = 33767721)
I don't know why my code is missing 1-digit. I appreciate it if someone helps me with this coding.
Thank you.
____________________________________________________________
n= input('Enter the length random number : ');
lmt= input('How many number you want to generate: ');
seed=5673;
disp('SN Random Numbers ')
disp('--- -------------- ')
for i=1:lmt
temp=num2str(seed^2);
s=size(temp);
st=(s(1,2)/2);
x=str2num(temp(st:(st+n-1)));
fprintf('%d %d\n',i,x);
seed=x;
end
___________________________________________________________
1 个评论
dpb
2021-1-29
size(temp) returns the size of the character string representation of the squared seed value. In MATLAB, even a char string is an array and size() returns the row, column sizes in that order. So, then s(1,2) is the second entry in the s array or the number of columns (characters) in the char() string vector, temp.
This could be written more simply for a single character string as either
st=length(s)/2; % length returns max(size(s))
or as
st=numel(s)/2;
eliminating the explicit call to size() entirely and the need to subscript it to pull the second value from the s array.
NB: that the division will return a fraction if the character string is ever an odd length.
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!