String output in MATLAB - matlab

clc
clear all
ii=1;
S =cell(size(30,1)); % cell size.
for ii=1:1:3
rand_id= rand(1,1) *3; % Randomly generte a number between 1 to 3.
if (rand_id<1)
rand_id=1; % 0 is ommitted.
else rand_id=floor(rand_id);
end
% rand_id will be used to open a previously saved file randomly.
if (rand_id==1)
f_id_1=fopen('C1.txt','r'); % Open and read a file.
elseif (rand_id==2)
f_id_1=fopen('C2.txt','r'); % Open and read a file.
end
% saning the file to read the text.
events_1=textscan(f_id_1, '%s', 'Delimiter', '\n');
fclose(f_id_1);
events_1=events_1{1}; % saving the text.
rand_event=events_1{randi(numel(events_1))}; % selects one text randomly.
S{ii}=rand_event;
end
I wrote the above code to randomly select a file. The file contains number of sentences. My aim is to randomly pick a sentence . I did that. Now, my problem is I cant save all the picked sentences inside the loop.
When I declare S(ii)=rand_event It shows error. When I try S(ii)=rand_event(ii) It only returns 1, 2, 3 characters in the three loops.
Please help.

S(ii)
is considered to be a matrix with well defined dimensions. I guess that your 'sentences' have different length. One solution might be to use a cell array.
S{ii}=rand_event
Cell arrays use curly braces.

Related

Matlab code Sha-1 hashing password

clc;clear all;close all;
fileID = fopen('H:\dictionary.txt');
S = textscan(fileID,'%s','Delimiter','\n') ;
fclose(fileID);
S = S{1} ;
% remove empty cells
S = S(~cellfun('isempty',S));
n=length(S);
k=0;
for i=1:n
for j=1:n
k=k+1;
y(k,1)=strcat(S(i),S(j))
end
end
This is my code for sha-1 hashing. where i am getting problem in for loop to generate all possible combinations in line
y(k,1)=strcat(S(i),S(j)).
its running properly. but its taking too long. i have been running this code for 2 days still its not getting over as my dictionary contains over 5000 words. please suggest me some good idea to do faster and some better way to improve and crack it.
Since you did not provide some data to test the code, I created my own test data, which is a cell array containing 400 words:
% create cell array with a lot of words
S = repmat({'lalala','bebebebe','ccececeece','ddededde'},1,100);
Here is the code with some small changes but with huge impact on the performance.
Note that the variable 'y' is here named 'yy' so that you can just copy and paste the code to compare it with your existing code:
% Preallocate memory by specifying variable and cell size
yy = cell(n^2,1);
% Measure time
tic
k = 0;
for i=1:n
for j=1:n
k=k+1;
% Replace strcat() with [] and index cell content with S{i} instead
% of indexing the cell itself with S(i)
yy{k}=[S{i},S{j}];
end
end
% Stop and output time measurement
toc
With my examplary data, your code took 7.78s to run and the improved and proposed code took 0.23s on my computer.
I would recommend to read the Matlab docs about Preallocation.

Sequence of data in MATLAB

I have sequence of data in MATLAB: data1, data2, data3,.... I want to print them one after one. I am stuck on that.
clear; clc;
data1=[1,2];
data2=[3,4];
n=[1,2];
for i=1:length(n)
fname(i,:)=sprintf('data%d',n(i));
end
Does this work for you?
clear; clc;
data1=[1,2];
data2=[3,4];
n=[1,2];
for i=1:length(n)
eval(['data' num2str(n(i))])
end
A possible solution not involving the use of eval could be the following.
Basically it consists of the following steps:
Get the list of data in the Workspace (with who function)
Identify the data to be printed (using regexp to identfy the variables names of the form dataxwhere x is a number)
save these variables in a temporary .mat file
load the .mat file in a struct which allows to have only the variables to be printed
exploit the dynamic field names to get access to the variables
This the code:
% Define some data
data1=[1,2];
data2=[3,4];
data3=rand(5)
data4a=rand(5)
dataaaa3=rand(5)
var_1=1
b=2
% Get the list of data in the Workspace
str=who
% Identify the data to be printed
var_to_print=regexp(str,'data\d$')
idx=~cellfun(#isempty,var_to_print)
% Down select the variables to be printed
str{idx}
% Generate a temporary ".mat" filename
tmp_name=[tempname '.mat']
% Save the data to be printed in the temporary ".mat" file
save(tmp_name,str{idx})
% Load the data to be printed into a struct
v=load(tmp_name)
% Get the names of the varaibles to be printed
f_name=fieldnames(v)
% print the value of the variables
for i=1:length(f_name)
[char(f_name(i)) ' = ']
v.(f_name{i})
end
% Move the temporary ".mat" file in the recycle folder
recycle('on')
delete(tmp_name)
Hope this helps.
Qapla'

create a huge text file in matlab with specific numbers?

How can I create a huge text file in matlab with millions of lines which contanin numbers 9876543210 and 5 emptyspace and again repeated numbers and 5 spaces for milions of lines?
myNumbers= (0:9);
fid = fopen('lastFile.txt','wt');
for i=1:99
fprintf(fid,'%d%d%d%d%d%d%d%d%d%d \r',myNumbers);
end
fclose(fid);
Loopy way:
myNumbers= (0:9);
repeats = 20; %// number of times to repeat array on each line
lines = 99; %// number of lines to write to file
fid = fopen('lastFile.txt','wt');
for n=1:lines
for r=1:repeats
fprintf(fid,'%d%d%d%d%d%d%d%d%d%d ',myNumbers); %// no return just yet
end
fprintf(fid, '\n'); %// or \r if that's what you really want
end
fclose(fid);
I changed the \r to \n because it made more sense to me. Unless you're using Mac OS 9. I also changed the one space at the end of the format specification to 5 spaces, since that's what you said you wanted.
To get the array to repeat on one line, you just have to make sure you don't add the newline until you've got everything you want on that line. Then do that for however many lines you want.
There are other ways to do this, but this is the most straightforward.

Matrix segmentation into files in Matlab

I have a very large matrix (M X N). I want to divide matrix into 10 equal parts (almost) and save each of them into a separate file say A1.txt, A2.txt, etc. or .mat format. How can I do this ?
Below is a code to divide a matrix into 10 equal parts and data_size is (M / 10).
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
save data(i).mat data
% What should I write here in order to save data into separate file data1.mat, data2.mat etc.
end
You said you wanted it in either txt format or mat format. I'll provide both solutions, and some of this is attributed to Daniel in his comment in your post above.
Saving as a text file
You can use fopen to open a file up for writing. This returns an ID to the file that you want to write to. After this, use fprintf and specify the ID to the file that you want to write to, and the data you want to write to this file. As such, with sprintf, generate the text file name you want, then use fprintf to write data to your file. It should be noted that writing matrices to fprintf in MATLAB assume column major format. If you don't want your data written this way and want it done in row-major, you need to transpose your data before you write this to file. I'll provide both methods in the code depending on what you want.
After you're done, use fclose to close the file noting that you have finished writing to it. Therefore, you would do this:
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
filename = sprintf('A%d.txt', i); %// Generate file name
fid = fopen(filename, 'w'); % // Open file for writing
fwrite(fid, '%f ', data.'); %// Write to file - Transpose for row major!
%// fwrite(fid, '%f ', data); %// Write to file - Column major!
fclose(fid); %// Close file
end
Take note that I space separated the numbers so you can open up the file and see how these values are written accordingly. I've also used the default precision and formatting by just using %f. You can play around with this by looking at the fprintf documentation and customizing the precision and leading zero formatting to your desire.
Saving to a MAT file
This is actually a more simpler approach. You would still use sprintf to save your data, then use the save command to save your workspace variables to file. Therefore, your loop would be this:
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
filename = sprintf('A%d.mat', i); %// Generate file name
save(filename, 'data');
end
Take note that the variable you want to save must be a string. This is why you have to put single quotes around the data variable as this is the variable you are writing to file.
You can use
save(['data' num2str(i) '.mat'], 'data');
where [ ] is used to concatenate strings and num2str to convert an integer to a string.

adding a matrix with appending using dlmwrite in matlab

I need to write two different matrices in a file. However, first matrix is just initial values=> 25*ones(10,10). Second matrix is also 10x10 matrix , and updating in every iteration. My question is , first matrix will be on the beginning of the file, later on second matrix will be appending the end of the first matrix after each iteration and updating. I dont want to overwrite the second matrix everytime, which is happening when i run these codes
My codes are like this:
if ss==5000;
dlmwrite('d:\Temp.txt',Tin*ones(10,10), ' ');
dlmwrite('d:\Temp.txt', Tnew,'-append','roffset', 1, 'delimiter', ' ');
ss=0
end
Could you help me on this ?
Thanks in advance.
I've put together a complete example that demonstrates what I think you want.
If the file doesn't exist, it creates it and puts your first matrix inside it. If it does exist, it appends subsequent data
filename = 'd:\Temp.txt';
for ss=1:25000
if mod(ss,5000)==0
%generate some data to write
Tnew = rand(10,10);
if ~exist(filename,'file')
dlmwrite(filename,ones(10,10), ' ');
end
dlmwrite(filename, Tnew,'-append','roffset', 1, 'delimiter', ' ');
end
end