for loop in a function

조회 수: 11 (최근 30일)
Marco Yu
Marco Yu 2016년 6월 22일
댓글: Marco Yu 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)
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