Create a text file by matlab - matlab

I want to create a text file like this with Matlab but i don't know how should I do that.
range(0,25e-9,0+600e-9),range(0+600e-9,1e-4,1.000000e-03),range(1.000000e-03,25e-9,1.000000e-03+600e-9),range(1.000000e-03+600e-9,1e-4,2.000000e-03),range(2.000000e-03,25e-9,2.000000e-03+600e-9),range(2.000000e-03+600e-9,1e-4,3.000000e-03)
for example here I want to create 6 point and I can do it by myself. But if I want create 100 point or 500 point I have to use Matlab. I wrote a code and create a matrix something like this but what I want is different. It's my code but I cant use it.....
clc
clear
close all
stp1=25e-9;
stp2=1e-4;
A=600e-9;
B=1e-3;
i=3;
F=zeros(i,3);
for i=1:i
if i==1
F(i,1)=0;
F(i,2)=stp1;
F(i,3)=A;
else
if mod(i,2)==0
F(i,1)=F(i-1,3);
F(i,2)=stp2;
F(i,3)=(i/2)*B;
else
F(i,1)=F(i-1,3);
F(i,2)=stp1;
F(i,3)=F(i,1)+A;
end
end
end
for example this is my matrix:
` 0.0000e+000 25.0000e-009 600.0000e-009
600.0000e-009 100.0000e-006 1.0000e-003
1.0000e-003 25.0000e-009 1.0006e-003`
I want to put them in one line and this like this:
`range(0.0000e+000,25.0000e-009,600.0000e-009),range(600.0000e-009,100.0000e-006,1.0000e-003),range(1.0000e-003,25.0000e-009,1.0006e-003)`
you know I want to add range(A(1,1),A(1,2),A(1,3)),range(A(2,1),A(2,2),A(2,3)) to my text file.... I hope I have explained well that I want.

I've put some code together below to help move this along. Please comment and I can adjust (or others can post answers based on updated information).
I'm still not sure exactly what outcome you're after.
For reference, you can see examples of file I/O documentation for dlmwrite here and for fprintf here. Notice you can specify the delimiter with dlmwrite and the exact format with fprintf.
A = [0.0000e+000 25.0000e-009 600.0000e-009;
600.0000e-009 100.0000e-006 1.0000e-003;
1.0000e-003 25.0000e-009 1.0006e-003];
dlmwrite('TestFile.txt',A) % Example use of dlmwrite
B = range(A,2); % Range of the rows of A
dlmwrite('TextFile2.txt',B)
C = cell(size(A,1),1);
fileID = fopen('TestFile3.txt','w+');
formatstr = '%12s\r\n';
for k = 1:size(A,1)
C{k}=['range(A(' num2str(k) ',:)'];
fprintf(fileID,formatstr,C{k});
end
fclose(fileID);
Hope this helps.

Related

Matlab: Color of legend doesn't fit plot

I am writing a script, which imports several sample files. Afterwards it calculates ratios of different elements and save them in a double-array. I am plotting the first column of this file for all the sample files into one plot. Which is working well. But the legends causes trouble. I want, that it includes the filenames of the sample files. But the color of the legend doesnt fit. I give you here parts of my code. Because I think the calculations are not interesting for you.
directory_name=uigetdir('','Ordner mit Messungen auswählen');
[nur_file_name,pfad]=uigetfile({'*.csv','csv-files (*.csv)';'*.*','all Files'},...
'Die csv-Files der Proben oeffnen (probe_001.csv=',[directory_name '/'], 'Multiselect', 'on');
nur_file_name=cellstr(nur_file_name);
nur_file_name=sort(nur_file_name);
filename=strcat(pfad,nur_file_name);
anzahl_files=size(filename,2);
for xy=1:anzahl_files
fid_in=fopen(char(filename(xy)),'r');
This part above import several files and saves the filename. To handle the filename easier, I changed it to a string array (1 x number of files) with the name filename_s.
Now I do some calculations (shown below). In the end I have for all measurement files a double array called "Ratio". I try to plot it with the legend includig the filenames:
tmpImport = importdata(filename{xy},',');
element_RL = tmpImport.colheaders;
element_RL=string(element_RL);
intens_RL=tmpImport.data;
[anzahl_runs,anzahl_elemente]=size(intens_RL);
for k=1:anzahl_elemente
Background(k)=mean(intens_RL(:,k)); %
Sigma(k)=std(intens_RL(:,k));
end
SP_limit=Background+(4*Sigma);
[~, PosSr87] = ismember('87Sr+', element_RL);
SpalteSr87(:,1)=intens_RL(:,PosSr87);
[~, PosSr86] = ismember('86Sr+', element_RL);
SpalteSr86(:,1)=intens_RL(:,PosSr86);
is_SP = intens_RL > SP_limit;
intens_RL(is_SP)=1;
intens_RL(~is_SP)=0;
anzahl_runs1=size(intens_RL,1);
id = true(anzahl_runs1,1) ;
for k=1:anzahl_runs1
if any (intens_RL(k,:)==1)
Ratio(k,1)=SpalteSr87(k,:)/SpalteSr86(k,:);
id(k) = 0 ;
end
end
filename_s = matlab.lang.makeValidName(nur_file_name);
filename_s=string(nur_file_name);
%Plot:
[NumRows1 NumCols1]=size(Ratio);
figure(1)
title('Proben 87Sr/86Sr');
xlabel('Partikel');
ylabel('87Sr/86Sr');
for p=1:anzahl_files
h(p)= scatter(1:NumRows1, Ratio(:,1));
legendtext{p} = filename_s(1,p);
hold on
end
legend(h, legendtext)
end
Plot works, filenames in the legend works but the colours are not fitting. Please be aware that i delete some parts of the code, so some for loops makes sense if there is more ;-). I appreciate any help. Thank you really much. And please forgive if something is not the right term, I dont work with matlab so long.

How do I save the name of a MATLAB file from a list?

I am currently working with a script that saves matrices as .mat files from other .mat files. I need to save 96 separate files so I have a loop that goes through the matrix names. I need to have the matrices saved with specific titles, that I have saved the titles in cell arrays {}. However, when I use the save(filename,variable) function, I get an error saying:
Error using save
Must be a text scalar.
Error in File_Creator (line 35)
save(name,fname);
My matrices need to be named 'PHI_Af','PHI_Am' (so on until) 'SLR_EF' (so every cr value needs to have a matrix with every par value. Here is what I am currently attempting:
cr = {'Af','Am','As','Aw','BS','BW','Cs','Cw','Cf','Ds','Dw','Df','ET','EF'};
par = {'PHI','BLD','KS','LAMBDA','PSIS','SLR'};
underscore = {'_'};
%% i and j are parameters in a loop where i = 1:length(par) and j = 1:length(cr)
%% f is the variable currently storing the matrix
s.(horzcat(par{i},underscore{1},cr{j})) = f;
name = string(strcat(par{i},'_',cr{j},'.mat'));
fname = string(s.(horzcat(par{i},underscore{1},cr{j})));
save(name,fname);
When I replace 'fname' with a generic string e.g. 'f', then the command runs but all the matrices save as the same thing ('f'), which makes it extremely difficult to run them all in the same script later.
I hope somebody can tell me what I'm doing wrong or provide me with a better solution. Please let me know if I can provide any more information.
Thank you
Assuming that the matrix, f, changes in each iteration of the loop (due to some other code you didn't post), it seems like this is all the code you need:
cr = {'Af','Am','As','Aw','BS','BW','Cs','Cw','Cf','Ds','Dw','Df','ET','EF'};
par = {'PHI','BLD','KS','LAMBDA','PSIS','SLR'};
for i = 1:length(par)
for j = 1:length(cr)
% add code here that loads the matrix f
name = [par{i}, '_', cr{j}, '.mat'];
save(name, 'f');
end
end

Looping a Function in Matlab

total newbie here. I'm having problems looping a function that I've created. I'm having some problems copying the code over but I'll give a general idea of it:
function[X]=Test(A,B,C,D)
other parts of the code
.
.
.
X = linsolve(K,L)
end
where K,L are other matrices I derived from the 4 variables A,B,C,D
The problem is whenever I execute the function Test(1,2,3,4), I can only get one answer out. I'm trying to loop this process for one variable, keep the other 3 variables constant.
For example, I want to get answers for A = 1:10, while B = 2, C = 3, D = 4
I've tried the following method and they did not work:
Function[X] = Test(A,B,C,D)
for A = 1:10
other parts of the code...
X=linsolve(K,L)
end
Whenever I keyed in the command Test(1,2,3,4), it only gave me the output of Test(10,2,3,4)
Then I read somewhere that you have to call the function from somewhere else, so I edited the Test function to be Function[X] = Test(B,C,D) and left A out where it can be assigned in another script eg:
global A
for A = 1:10
Test(A,2,3,4)
end
But this gives an error as well, as Test function requires A to be defined. As such I'm a little lost and can't seem to find any information on how can this be done. Would appreciate all the help I can get.
Cheers guys
I think this is what you're looking for:
A=1:10; B=2; C=3; D=4;
%Do pre-allocation for X according to the dimensions of your output
for iter = 1:length(A)
X(:,:,iter)= Test(A(iter),B,C,D);
end
X
where
function [X]=Test(A,B,C,D)
%other parts of the code
X = linsolve(K,L)
end
Try this:
function X = Test(A,B,C,D)
% allocate output (it is faster than changing the size in every loop)
X = {};
% loop for each position in A
for i = 1:numel(A);
%in the other parts you have to use A(i) instead of just A
... other parts of code
%overwrite the value in X at position i
X{i} = linsolve(K,L);
end
end
and run it with Test(1:10,2,3,4)
To answer what went wrong before:
When you loop with 'for A=1:10' you overwrite the A that was passed to the function (so the function will ignore the A that you passed it) and in each loop you overwrite the X calculated in the previous loop (that is why you can only see the answer for A=10).
The second try should work if you have created a file named Test.m with the function X = (A,B,C,D) as the first code in the file. Although the global assignment is unnecessary. In fact I would strongly recommend you not to use global variables as it gets very messy very fast.

Parsing a data file in matlab

I have a text file with two columns of data. I want to split this file and save it as two individual strings in matlab, but I also need to stop copying the data when I meet an identifier in the data then stat two new strings.
For example
H 3
7 F
B B
T Y
SPLIT
<>
Where SPLIT <> is where I want to end the current string.
I'm trying to use fopen and fscanf, but struggling to get it to do what I want it to.
I tried the following script on the example you provided and it works. I believe the comments are very self explanatory.
% Open text file.
fid = fopen('test.txt');
% Read the first line.
tline = fgetl(fid);
% Initialize counter.
ii = 1;
% Check for end string.
while ~strcmp(tline, 'SPLIT')
% Analyze line only if it is not an empty one.
if ~strcmp(tline, '')
% Read the current line and split it into column 1 and column 2.
[column1(ii), column2(ii)] = strread(tline, ['%c %c']);
% Advance counter.
ii = ii + 1;
end
% Read the next line.
tline = fgetl(fid);
end
% Display results in console.
column1
column2
% Close text file.
fclose(fid);
The key functions here are fgetl and strread. Take a look at their documentation, it has some very nice examples as well. Hope it helps.

FSEEK error while running Matlab function

I got this error while running a function in Matlab
"Error using fseek Invalid file identifier. Use fopen to generate a valid file identifier."
May I know what is the possible causes of this error? I am very new to Matlab. Please help me. Thanks a lot
I am sorry if I should not post the overall function. But I am afraid the information I gave is not enough. The overall command of the function is:
function gau_hmm_init_train(traininglist_filename,model_filename,MODEL_NO,STATE_NO, dim )
if nargin == 0
traininglist_filename='training_list.mat' ;
model_filename='models.mat';
MODEL_NO=11;
STATE_NO=4;
dim=12;
end
MIN_SELF_TRANSITION_COUNT=0;
load(traininglist_filename,'list');
% allocate mean, var vectors, transition prob. for the of models
mean_vec_i_m=zeros(dim,STATE_NO,MODEL_NO);
var_vec_i_m=zeros(dim,STATE_NO,MODEL_NO);
A_i_m=zeros(STATE_NO,MODEL_NO);
vector_sums_i_m=zeros(dim,STATE_NO,MODEL_NO);
var_vec_sums_i_m=zeros(dim,STATE_NO,MODEL_NO);
fr_no_i_m=zeros(STATE_NO,MODEL_NO);
self_tr_fr_no_i_m=zeros(STATE_NO,MODEL_NO);
utterance_no=size(list,1);
total_fr_no=0;
for k=1:utterance_no
filename=list{k,2};
m=list{k,1}; % word ID
fid=fopen(filename,'r');
fseek(fid, 12, 'bof'); % skip the 12-byte HTK header
%fopen(fid, 12, 'bof'); % skip the 12-byte HTK header
c=fread(fid,'float','b');
fclose(fid);
fr_no=length(c)/dim;
total_fr_no=total_fr_no+fr_no;
c=reshape(c,dim,fr_no);
for i=1:STATE_NO
begin_fr=round( fr_no*(i-1) /STATE_NO)+1;
end_fr=round( fr_no*i /STATE_NO);
seg_length=end_fr-begin_fr+1;
vector_sums_i_m(:,i,m) = vector_sums_i_m(:,i,m) + sum(c(:,begin_fr:end_fr),2);
var_vec_sums_i_m(:,i,m) = var_vec_sums_i_m(:,i,m) + sum( c(:,begin_fr:end_fr).*c(:,begin_fr:end_fr) , 2);
fr_no_i_m(i,m)=fr_no_i_m(i,m)+seg_length;
self_tr_fr_no_i_m(i,m)= self_tr_fr_no_i_m(i,m) + seg_length-1;
end %for s=1:STATE_NO
end % for k=1:utterance_no
for m=1:MODEL_NO
for i=1:STATE_NO
mean_vec_i_m(:,i,m) = vector_sums_i_m(:,i,m) / fr_no_i_m(i,m);
var_vec_i_m(:,i,m) = var_vec_sums_i_m(:,i,m) / fr_no_i_m(i,m);
A_i_m(i,m)=(self_tr_fr_no_i_m(i,m)+MIN_SELF_TRANSITION_COUNT)/(fr_no_i_m(i,m)+2*MIN_SELF_TRANSITION_COUNT);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% tying of cov. matrices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
overall_var_vec=sum(sum(var_vec_sums_i_m(:,:,:),3 ),2)/sum(sum(fr_no_i_m,2 ),1);
for m=1:MODEL_NO
for i=1:STATE_NO
var_vec_i_m(:,i,m)=overall_var_vec;
end
end
%%%%%%%%%%%%%%%% end of cov. matrices tying
save(model_filename, 'mean_vec_i_m', 'var_vec_i_m', 'A_i_m');
fprintf('init. train complete \n');***
Sounds like the line fid=fopen(filename, 'r'). This filename comes from the list variable which is loaded from the file traininglist_filename, so you should check that these files exist. If you're passing it a traininglist_filename you should load this file in MATLAB and look at the contents of list; otherwise it will load the default 'training_list.mat', so you should look in there to make sure all the filenames are valid. Perhaps you're missing a file?
To continue the reply by #Wakjah, the training_list.mat file is missing from the reference path by the code you are using because it is automatically created at MATLAB default path. Therefore, just change the path at the 'Current Folder' to where you had open your current code and it should work.