for loop in a function

9 次查看(过去 30 天)
%function [temp_finalmean]=first_difference_mean
%calculate the first difference between two column
files=dir('*.mat');
temp_save=zeros(30,359);
for m= 1:length(files)
load(files(m).name)
temp_temp=zeros(30,359);
temp_thickness=cell2mat(T(1,1));
temp_thickness=image2polar(temp_thickness,peaks(1,1)*200/668,peaks(2,1)*200/668,'counterclockwise',[],1,pi/180,'linear');
temp_size=size(temp_thickness);
temp_thickness(62:temp_size(1),:)=[];
temp_thickness(1:31,:)=[];
disp(['Loading ' num2str(m) ' files'])
for n=1:359
for k=1:30
temp_temp(k,n)=temp_thickness(k,n+1)-temp_thickness(k,n);
end
end
temp_save=temp_save+temp_temp;
end
temp_finalmean=temp_save/length(files);
end
If I remove the top line and bottom line(i.e. the function and end),then I will have my code run perfectly. I mean I can get different result from the same code, it is strange... Is it I can't use load() in a function or something happened?
Thank you

采纳的回答

Walter Roberson
Walter Roberson 2016-6-22
When you have end matching function then you are creating a static workspace where it is not permitted to "poof" variables into existence using eval() or assignin() or evalin() -- and so, indirectly, also not using load() or syms() . You should use the output form of load() and pull the required information out of the structure that is returned.
  3 个评论
Walter Roberson
Walter Roberson 2016-6-22
function temp_finalmean = first_difference_mean
%calculate the first difference between two column
files = dir('*.mat');
temp_save = zeros(30,359);
for m = 1 : length(files)
data = load(files(m).name); %*
temp_temp = zeros(30,359);
temp_thickness = cell2mat( data.T(1,1)); %*
temp_thickness = image2polar(temp_thickness, data.peaks(1,1)*200/668, data.peaks(2,1)*200/668, 'counterclockwise', [], 1, pi/180, 'linear'); %*
temp_size = size(temp_thickness);
temp_thickness(62:temp_size(1),:) = [];
temp_thickness(1:31,:) = [];
disp(['Loading ' num2str(m) ' files'])
temp_temp = diff( temp_thickness(1:30, 1:360), [], 2 );
temp_save = temp_save + temp_temp;
end
temp_finalmean = temp_save / length(files);
end
The lines marked with %* are the essential changes; the other changes are style or efficiency (replacing the double loop with a single diff)
Marco Yu
Marco Yu 2016-6-22
Thank you so much :D you are an expert

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by