I am new on matlab and I don't know many things at the moment.
I have a script which create more than 100 figures. I want to save those figures in 3 different folders. Here is my code until now:
pridir='C:\Users\tasos\Desktop\folder';
figtxt1='folder1';
figtxt2='folder2';
figtxt3='folder3';
yM = load('pathtomydata');
[n,m]=size(yM);
maxtau2 = 10;
alpha = 0.05;
zalpha = norminv(1-alpha/2);
p=6;
for i=1:m-1
for j=i+1:m
figure()
y1V=yM(:,i);
y2V=yM(:,j);
plot(y1V,'b')
hold on
plot(y2V,'r')
legend(sprintf('text= % d',i),sprintf('text= % d',j))
title('My Title')
printto = sprintf('%s%d\\text%d and %d.jpg',pridir,i,i,j);
print('-djpeg90',printto)
close(gcf)
end
end
If I left my code like this, all the figures created but they didn't save on folders. If I remove the "%" from the last two lines, I have the following error
Error using name (line 103)
Cannot create output file 'C:\Users\tasos\Desktop\folder1\text1 and 2.jpg'
Error in print (line 206)
pj = name( pj );
Error in test (line 25)
print('-djpeg90',printto)
P.S. I am using the R2012b version
Avoid eval()!
Define one generic print directory:
pridir = 'C:\Users\***\Desktop\fold';
Then inside the inner loop:
printto = sprintf('%s%d\\figuretext %d and %d.jpg',pridir,i,i,j);
print('-djpeg90',printto)
where printto will be something like:
C:\Users\***\Desktop\fold1\figuretext 1 and 3.jpg
Also, you might want to close the figure after the print: close(gcf).
NOTE: the directories where you're gonna save the files should already exist, otherwise create them with mkdir() before saving any pictures.
I think matlab changed the code for writing a folder with the 2013 version.
I changed 'XX\YY\ZZ.pjg'
To:
'XX/YY/ZZ.pjg'
And it worked for me, strangely.
Related
I have multiple files that I want to open using fopen. The files have a similar pattern, I have tried to use a for loop as follows, but it does not work. Any ideas how to open each file. Thanks in advance.
for ii = 0:12
file = fprintf('population_%d.dat', ii); % -----> File names
generations_fid = fopen(file); % Question ???
matrix = {};
while ~feof(generations_fid)
generations = cell2mat(textscan(generations_fid, repmat('%f', 1, (3))));
if isempty(generations)
fgetl(generations_fid);
else
matrix{end+1} = generations;
end
end
end
You want to be using sprintf to dynamically generate the file name, not fprintf.
file = sprintf('population_%d.dat', ii);
It's also good practice to open your file with the required permissions. In your case, it looks like you're reading, so you should use
generations_fid = fopen(file, 'r');
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.
I have this piece of MATLAB code:
path(path,'./Classes');
locationID = 'Z8Ksof1rzm';
poolobj = gcp('nocreate');
if isempty(poolobj)
parpool(4)
else
%do nothing. we already have parpool running
end
myFiles = dir(strcat('./exportParse/exportLocation_', locationID));
MachineData = cell(length(myFiles)-2,1);
disp(myFiles)
parfor iFile =3:length(myFiles)
jsonFile = myFiles(iFile).name;
MachineData{iFile-2} = loadjson(strcat('./exportParse/exportLocation_', locationID,'/',jsonFile));
end
The script runs pretty well from the MATLAB desktop. I see no errors and I get all 4 processors working on the json parsing. At the end, I get MachineData filled with the desired information. All good.
The problem occurs when I call
matlabPath="/Applications/MATLAB_R2014b.app/bin/matlab -nodesktop -nosplash -r"
$matlabPath "run myScript.m"
where myScript.m is the file containing the code above. The script won't run again, it says this:
10x1 struct array with fields:
name
date
bytes
isdir
datenum
Error using readDataAprocam (line 17)
Improper index matrix reference.
Error in run (line 63)
evalin('caller', [script ';']);
as you can see, the line dis(myFiles) returns a valid struct array of files.
Line 17 is the line of the parfor command.
Note that on the shell and in MATLAB I'm located on the same path. I also shut down the parpool on the matlab desktop so the script running from the shell can claim it. there is no problem here as well.
What does Improper index matrix reference means on this context? Why does it run from the matlab desktop and not from the shell?
I'm running Mac OS X 10.11.3 and MATLAB 2014b.
I'm not sure what I did, but I got rid of this error. My code looks like this now:
myScript.m:
%% settings
path(path,'./Classes');
locationID = 'Z8Ksof1rzm';
poolobj = gcp('nocreate');
if isempty(poolobj)
parpool(4)
else
%do nothing. we already have parpool running
end
%% get files
disp('ok. lets try it')
myFiles = dir(strcat('./exportParse/exportLocation_', locationID,'/export*'));
MachineData = cell(length(myFiles),1);
parfor iFile =1:length(myFiles)
data = importJSONFile(iFile,locationID,myFiles);
MachineData{iFile} =data;
end %looping over files
MachineData
Script importJSONFile:
function data = importJSONFile(fileIndex,locationID,myFiles)
jsonFile = myFiles(fileIndex).name;
filePath = strcat('./exportParse/exportLocation_', locationID,'/',jsonFile);
data = loadjson(filePath);
%data = struct;
end
The code runs from the shell ONLY if I change the parfor to for. if I leave the parfor it will trow the error
Error using myScript (line 16)
Conversion to char from cell is not possible.
Error in run (line 63)
evalin('caller', [script ';']);
Line 16 is the parfor line.
... but, I got rid of the error above.
So, as I browse through google on the problem of how to create a .gif animation from series of .fig files, i stumble through one that uses .sdf file, I tried to rewrite the program to work for my .fig files
clear all;
close all;
dynam = 156;
gif_fps = 24;
video_filename = 'A.gif';
fh = figure(1);
for i = 1:dynam
F_data = getdata(['F' num2str(i,'_%03i', '.fig');
imagesc(F_data);
drawnow;
frame = getframe(fh);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if a == 0;
imwrite(imind,cm,video_filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,video_filename,'gif','WriteMode','append','DelayTime',1/gif_fps);
end
end
so it pops up an error saying
??? frame = getframe(fh);
|
Error: The expression to the left of the equals sign is not a valid target for an assignment.
which I don't understand why this is happening, and I also notice that Matlab is not drawing the figs, the figure that pop us is completely blank.
The error comes from a typo. The line
F_data = getdata(['F' num2str(i,'_%03i', '.fig'); %bracket missing at the end
should read
F_data = getdata(['F' num2str(i,'_%03i', '.fig']);
Without the bracket, Matlab sees
['F' num2str(i,'_%03i', '.fig');
imagesc(F_data);
drawnow;
frame
as a single string of letters. The code's logic is therefore a = b = c and matlab can't interpret this.
To prevent such errors, matlab and its editor have some nice coloring schemes that highlight in dark red the text following an opening string ', and turn the full string in purple when a closing ' is used. If you see some red characters spanning over several lines, that's a sign of a potential problem. Unfortunately, brackets don't have such behavior...
Additionnaly, what about opening the figures per se? You will see if each figure renders well (no blank) and will be able to capture the frame.
for i = 1:dynam
%open, get the frame from and close the figure
fh_tmp = open(['F' num2str(i,'_%03i', '.fig'])
frame = getframe(fh_tmp);
close(fh_tmp);
im = frame2im(frame);
...
I still struggle to find where the getdata is coming from.
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.