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!
Mostra commenti meno recenti
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
Risposta accettata
Più risposte (1)
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 Commenti
Randy st
il 8 Mag 2017
Yeah, you've still got the xlswrite inside the loop instead as I showed, after the loop to write the whole array in "one swell foop".
So, you've ovewritten the same location (A1) every pass.
function [Max, Time_Half]= Mathworks_HalfMaxtimes()
delimiter = ',';
startRow = 25;
fmt=[repmat('%f',1,2) '%*[^\n]'];
pn = uigetdir(pwd,'matlabbatch');
d=dir(fullfile(pn, '*.csv'));
L=length(d);
for i=1:L
fid=fopen(d(i).name,'r');
dataArray=cell2mat(textscan(fid, fmt, 'Delimiter', delimiter, ...
'headerlines', startRow ...
'collectoutput',1));
fid=fclose(fid);
Time_Hrs = dataArray(:,1);
Resis_Cap = dataArray(:,2);
Max=zeros(L,1);
MaxHalf=Max;
Time_Half=Max;
for i=1:length(d)
MaxHalf(i)=max(Res_Ohm1)/2;
Max(i)= max(Res_Ohm1);
tmp=abs(Res_Ohm1-MaxHalf(i));
[~,idx] = min(tmp);
Time_Half(i) = Time_Hrs1(idx);
end
xlswrite('Time_Half_Max.xlsx', [Max Time_Half])
end
Let's "simplify, simplify"...cut it down to the bare basics first and get that working; THEN you can do other things without all the obfuscation hindering seeing the trees for the forest.
First, since you don't do anything but str2double on the values returned, there's no need to have read them as strings to begin with...change the format string to '%f' instead and do the conversion when reading the file.
Second, you haven't defined ResistanceOhm1--what is it and where does it come from? Need that before anything will work. Note that I shortened the name significantly; excessively-long variable names just clutter up the code by adding more noise than they clarify anything. Keep meaningful names, 'a' isn't meaningful, but something 20 characters long is just too hard to keep straight.
What the rest is supposed to be and what it needs to be to accomplish that depends entirely upon what that variable is--is it fixed over all files, is it a constant that changes for each file, is it a vector of values for each file, ...???
Without that, there's nowhere else to go.
Once one gets that done, then you can go back and and in some of the plotting and other niceties, but got to solve first things first.
dpb
il 9 Mag 2017
Well, you might tell us where, at least. Post the error in context...
Randy st
il 9 Mag 2017
That doesn't seem feasible from the code posted... max() only returns a single value from a vector.
BUT, you've got much bigger issues than this, you've duplicated the code loops twice??? Why didn't you use the code I gave before? I defined L as length(d) simply to keep from calling the same function on the same array multiple times; now you've moved the preallocation code inside the loop over the files where you'll wipe out what you did for the preceding file every time and then for some unknown reason started yet another loop inside that...
Go back to the earlier version...what do you think is wrong with what I wrote as is?
Unless you're doing something different than what you described, that should work as it stands, barring typos and any aha! moments which are always possible working from afar, of course.
Anyway, let's start with that and get it to work instead of going back to square one all the time.
Also, please learn to use the code formatting; I know it's a kluncky interface, I've bi...er, complained at length about it to TMW but it is what they've provided. (:
Either
- highlight the code section and then use the {}Code button, or
- Using two blank spaces at beginning of code line will switch out of word wrap mode so you set cursor at that point and paste.
dpb
il 9 Mag 2017
OK, sorry I let self get upset...it's not quite as bad as first thought...most of what I had is there, you just duplicated some stuff I don't understand why...
Up to and including looks ok.
...
L=length(d); % so now preallocate knowing length...
RMax=zeros(L,1); <<<ERROR
RMaxHalf=RMax;
RTime_Half=RMax;
% and loop over the files...
for i=1:L
fid=fopen(d(i).name,'r'); %opening file # i
dataArray=cell2mat(textscan(fid, fmt, 'Delimiter', delimiter, 'headerlines', startRow, 'collectoutput',1));
fid=fclose(fid); %closing the file
Time_Hrs = dataArray(:,1);
Res = dataArray(:,2);
RMax(i)= max(Res);
RMaxHalf(i)=Res/2;
tmp=abs(Res-RMaxHalf(i));
[~,idx] = min(tmp);
RTime_Half(i) = Time_Hrs(idx);
end
xlswrite('Time_Half_Max.xlsx', [RMax RMaxHalf])
Again, the loop is over the files and you're saving one value per each file for each variable which is a vector. Matlab works on vectors, you don't need another steenkin' loop! inside the one.
Randy st
il 9 Mag 2017
"...but Rmax(i) below is not a single element vector"
This makes no sense at all.
Res = dataArray(:,2);
Res will be a column vector by the above; selects all rows of the second column.
Ergo, max(Res) will be a single value, the maximum of that vector unless you've somewhere aliased max the builtin function.
Thus, there can be no more than one element to be assigned to RMax(i)
Whatever it is, it isn't that nor the preallocation; it's somewhere you're not showing in enough context to be able to see.
Demo:
>> Res=randn(30,1); % simulate your vector
>> max(Res) % max() is just one value
ans =
3.5784
>> Res([3 5 23])=Res(1); % make some duplicates
>> max(Res) % and still only the one returned
ans =
3.5784
>>
So, as said, it isn't what you think; set a breakpoint before that line and look at sizes of all variables up to that point and see where something isn't what think it is.
Of course,
which max
at the command line wouldn't hurt to see what you're actually executing when max is called. If it isn't the builtin, "Houston, we have a problem!"
clear max
will take care of it if you have somehow managed to do that...
dpb
il 10 Mag 2017
OK, I took your code and pasted it into the editor so could format it legibly...and then can see what overlooked before...
The problem is related to what I asked before about what you intended that never resolved...
...
RMaxHalf(i)=Res/2;
There's the problem; Res is still the vector; what is RMaxHalf supposed to be...is it just
RMaxHalf(i)=Rmax(i)*/2;
??? Why did you leave the whole vector there I asked before quite some time back...
Then, what's the intent of the next stuff with
tmp=abs(Res-RMaxHalf(i));
[~,idx] = min(tmp);
??? I don't know what you're trying to compute here, but you've got similar problem in mixing up what are single values with vectors.
Need the definition of what the results are supposed to be first instead of just trying to make something run.
Randy st
il 10 Mag 2017
Randy st
il 10 Mag 2017
On the first, yes, I'm sure, I just demonstrated to you it isn't the issue. The problem is the next line where you try to assign
RMaxHalf(i)=Res/2;
Why would you take max(Res) twice in succession in two lines of code???? You had just found the max value and saved it; why make the computer do all the work to find the same number twice???
RMax(i)= max(Res);
RMaxHalf(i)=RMax(i)/2;
is identically the same value at zero additional cost.
The subsequent lines ending may be ok; it will execute but not sure what the min() of that difference means, but it's certainly legal to do what you've done albeit "the Matlab way" would do without the temporary.
[~,idx] = min(abs(Res-RMaxHalf(i)));
RTime_Half(i) = Time_Hrs(idx);
Randy st
il 10 Mag 2017
Put lines
size(Res)
size(max(Res))
whos Rmax
just before that line then and show the full context of the error including what those lines show and the code EXACTLY as you ran it...it's gotta' be something not being shown 'cuz that can't error that way as I showed in previous demo--if Res is a vector, then max(Res) must be a single value.
ADDENDUM
OK, I ran the copy of the code I created here...there's one way to get the mismatch in sizes I hadn't thought of--that's if Res is empty; iow, you didn't successfully read any data...I never use the directory selection as you did (not that that's necessarily bad, it's just not the way I code) so if you're not in the directory choose, then the fopen may fail or the .csv files aren't necessarily the ones wanted and I presumed from the dir it'd be guaranteed.
What need is where did
d=dir(fullfile(pn, '*.csv'));
and used specific path,
fid=fopen((fullfile(pn,d(i).name,'r'));
do same thing in the fopen call as well to be same files. You also need to do same on the filename in the xlswrite call, too, if that's where you want that file, otherwise it'll end up in the current working directory instead.
That SHOULD fix your problem; the above diagnostics will point to the issue likely; the other possibility is the textscan call didn't succeed if the data aren't matching up to the format string.
A test on the size(dataArray) would let you check on that, but just use debugger after the above fixup and ensure you're reading the files you think you are and the data are actually being read in.
I just never thunk of it being empty...empty is certainly also not the same size as one. :)
But, lesson is, USE THE DEBUGGER!! when things aren't making sense.
PS: If you want this RMaxHalf() array, too, then you also need to preallocate it.
Randy st
il 10 Mag 2017
dpb
il 11 Mag 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.
Categorie
Scopri di più su Spreadsheets in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!