Effacer les filtres
Effacer les filtres

Can someone explain to me how I can format the function to output only Max and Half_max into an excel file, for each file in the loop? Thanks!

1 vue (au cours des 30 derniers jours)
function []= Mathworks_HalfMaxtimes()
% set fixed parameters
delimiter = ',';
startRow = 25;
fmt=[repmat('%s',1,2) '%*[^\n]'];
% scan directory requested
pn = uigetdir(pwd,'matlabbatch');
d=dir(fullfile(pn, '*.csv'))
dir(fullfile(pn, '*.csv'))
% loop over found files
for i=1:length(d)
fid=fopen(d(i).name,'r');
dataArray = textscan(fid, fmt, 'Delimiter', delimiter, ...
'headerlines', startRow, ...
'ReturnOnError', false);
fid=fclose(fid);
%%Allocate imported array to column variable names
Time_Hrs = dataArray{:, 1};
Resis_Cap = dataArray{:, 2};
Time_Hrs1=str2double(Time_Hrs);
Resistance_Ohm1=str2double(Resis_Cap);
%Plot Orginal Figure
figure( 'Name', 'Orig' );
h = plot( Time_Hrs1, Resistance_Ohm1);
legend( h, 'RorC vs Time', 'untitled fit 1', 'Location', 'NorthEast' );
% Perform the 1/2 Time Operation
MaxHalf= max(Resistance_Ohm1)/2; %value to find
Max= max(Resistance_Ohm1)
tmp = abs(Resistance_Ohm1-MaxHalf);% Taking the capicitance values and subtracting the 1/2 max from the vector
[minimum idx] = min(tmp); %index of closest value, finding the row at which the value is closest to 0
Time_Half = Time_Hrs1(idx) %closest time;
% Label axes with half max
xlabel('Time(hrs)')
ylabel('ResistanceorCapacitance')
grid on
deriv=h
hold on
plot([Time_Half,Time_Half], [0,MaxHalf]);
str= ('Half-max');
text(Time_Half,MaxHalf, str)
A=xlswrite('Half_Max.xlsx', Max);
end

Réponse acceptée

dpb
dpb le 10 Mai 2017
Modifié(e) : dpb le 10 Mai 2017
OK, after all the above discussion, here's the function I tested on a file with two CSV-separated numeric columns.
It also has at least rudimentary error checking to ensure
  1. a file is found, hence will be opened
  2. the data read succeeded to the point at least DataArray isn't empty
Hopefully that will be enough to get you started...btw, there's a third variable calculated that isn't in your return list if you care about perhaps having it available other than in the Excel file...
As noted, the only logical explanation for the previous assignment error is that the vector was empty which I had not considered; besides "just knowing" the code would work if appropriate file(s) were available, I had presumed you would have checked that the reading portion was working, at least.
function [RMax, RMax_Half]= Mathworks_HalfMaxtimesRational()
delimiter = ',';
startRow = 25;
fmt=[repmat('%f',1,2) '%*[^\n]'];
pn = uigetdir(pwd,'matlabbatch');
d=dir(fullfile(pn, '*.csv'));
% if no match, abort, tell user
if isempty(d),error(['DIR: no files matched ' fullfile(pn, '*.csv')]),end
% found at least one so can continue
L=length(d);
RMax=zeros(L,1);
RMax_Half=RMax;
RTime_Half=RMax;
% and loop over the files...
for i=1:L
msg='';
[fid,msg]=fopen(fullfile(pn,d(i).name),'r');
error(msg) % should never fail here w/ above check
dataArray=cell2mat(textscan(fid, fmt, ...
'Delimiter', delimiter, ...
'headerlines', startRow, 'collectoutput',1));
fid=fclose(fid); %closing the file
% if no data, abort, tell user
if isempty(dataArray),error(['No data from ' fullfile(pn,d(i).name)]),end
Time_Hrs=dataArray(:,1);
Res=dataArray(:,2);
RMax(i)= max(Res);
RMax_Half(i)=RMax(i)/2;
[~,idx] = min(abs(Res-RMax_Half(i)));
RTime_Half(i) = Time_Hrs(idx);
end
xlswrite(fullfile(pn,'Time_Half_Max.xls'), [RMax RMax_Half RTime_Half])
fprintf('Time_Half_Max.xlsx\n')
fprintf('%.2f %.2f %.2f\n', [RMax RMax_Half RTime_Half].') % what wrote
PS: Can't overemphasize how valuable the debugger is--and it's trivial to use; just click on a line in the LH margin by the line numbers and start the function from the command line. You can then explore what's happening as you step through, seeing variables as they are inside the function to find such problems far more quickly than we can do so here...
  7 commentaires
dpb
dpb le 11 Mai 2017
Modifié(e) : dpb le 11 Mai 2017
As for the file, way, way, way back I wondered that there may be an "off by one" error in the 'headerlines' count just reading that initial auto-generated code.
I was sure I had mentioned that, but looking back, I can't seem to find where so mayhaps I didn't but just thought had.
Anyway, if you look at the file, the column header is in line 26; the data start in row 27; but are using 'headerlines',25 so it's trying to read that header as a number and fails. In the original auto-generated code, it was read as string so didn't matter but made the conversion later in str2double. Why is anybody's guess altho if do read as the cellstr array if the column header is significant can use it to create a table or to label output...
Anyways, again, the key is to use error-checking and the debugger to find why things aren't working as expected when results aren't those expected...
Fix it to match the actual file format.
Randy st
Randy st le 11 Mai 2017
It works! Thanks a lot! I'm currently taking a MATLAB basics course and I hope to be a bit more competent at the end:)

Connectez-vous pour commenter.

Plus de réponses (1)

dpb
dpb le 5 Mai 2017
Modifié(e) : dpb le 5 Mai 2017
As I suggested earlier, you need to add some array handling/outputs to your function...
MaxHalf=zeros(length(d),1); % preallocate result array
Max=MaxHalf; % ditto...
for i=1:length(d)
...
% Perform the 1/2 Time Operation
MaxHalf(i)=max(Resistance_Ohm1)/2;
Max(i)= max(Resistance_Ohm1)
...
end
xlswrite('HalfMax_Max.xlsx', [Max MaxHalf])
ADDENDUM
Of course, having written one, the other is pretty easy to derive! :) (Of course, need to know which it is if only one in the file; pretty easy to tell with both! :) )
xlswrite is quite slow so save up all the values and write in "one swell foop" at the end instead of calling every time. Plus, if did the other way, would have to keep an R,C location to prevent overwriting the same data every time.
  19 commentaires
Randy st
Randy st le 10 Mai 2017
Here is the code I currently have
if true
% code
end
%Grabbing your folder,grabbing files of interest, assigning length of folder, formatting documents,
delimiter = ','; %The comma is used to separate matrix subscripts and arguments to functions.
startRow = 25; %specifying the first row you want data from
fmt=[repmat('%f',1,2) '%*[^\n]']; %The fmt variable is the format string that maps the content of the file to the data variables you want returned--above it is two string variables and then an idiom to skip the rest of each record (line).
pn = uigetdir(pwd,'matlabbatch'); % Getting directory/folder from memory
d=dir(fullfile(pn)); %getting specific files from directory/folder
L=length(d); % so now preallocate knowing length...
RMax=zeros(L,1);
RTime_Half=RMax;
% and loop over the files...
for i=1:L
fid=fopen(d(i).name,'r'); %openingdbs file # i
dataArray=cell2mat(textscan(fid, fmt, 'Delimiter', delimiter, 'headerlines', startRow, 'collectoutput',1));
fid=fclose(fid); %closing the file
Time_Hrs = dataArray(:,1);
What changes do I need to make? I'm not sure how dir and fopen work , that part of the code was given to me...
dpb
dpb le 11 Mai 2017
"I'm not sure how dir and fopen work , that part of the code was given to me..."
Read the doc to learn how they work; don't rely on somebody else entirely.

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by