simple for loop problem
10 次查看(过去 30 天)
显示 更早的评论
Hi there,
I have a problem with some unwanted low value sections in my dataset, which I manually need to adjust. At the moment I'm trying to automate the process, which hopefully will speed up everything a bit. I managed to find the positions of these low value sections using the "find" function.
uplim=max(hd);
lowlim=max(hd)-mean(hd);
adj=find(hd<lowlim);
As there are more than just one low value section, I'm trying to break these up into individual sections. So firstly I found the end position of each section:
test=zeros(length(adj),1);
for i=1:(length(adj)-1);
test(i,1)=((adj(i+1,1)-adj(i,1)));
end
endsec=find(test>1);
What I would like to do know is to write a simple loop, which splits these section up and saves them seperately, so that I can call them back and adjust individually. I think I just need a simple loop, but I'm not very good with Matlab and I always struggle with these. I started with something like that:
for i=1:length(endsec)
sec(i,1)=adj(endsec(i,1):endsec(i,1),1)
end
But of course this doesn't work as I'm calling back the same values. I think I need to create a loop in the loop, but I can't find a smart way to do it. I need to get a loop which creates an output like this:
1st loop
sec(1,1)=adj(1:endsec(1,1),1)
2nd loop
sec(2,1)=adj(endsec(1,1)+1:endsec(2,1),1)
3rd loop
sec(3,1)=adj(endsec(2,1)+1:endsec(3,1),1)
Any suggestions are highly appreciated. Also if you have a better solution than a loop for this problem!
Many thanks for your help, Astrid
0 个评论
采纳的回答
Andrei Bobrov
2012-4-8
lowlim=max(hd)-mean(hd);
t = hd<lowlim;
t2 = find([true;diff(t)~=0]);
id = t2(bsxfun(@plus,find(t(t2)),[0 1]));
id(:,2) = id(:,2)-1;
out = arrayfun(@(ii)id(ii,1):id(ii,2),(1:size(id,1))','un',0);
OR
lowlim=max(hd)-mean(hd);
t = [0, (hd<lowlim).', 0];
out = arrayfun(@(i1,i2)i1:i2,strfind(t,[0 1]),strfind(t,[1 0])-1,'un',0);
0 个评论
更多回答(4 个)
Image Analyst
2012-4-8
I don't think you need all those loops. First, tell us what you would do to the low value sections to "adjust them individually." Would you set all those elements to some minimum value:
lowIndexes = hd < lowlim;
hd(lowIndexes) = lowlim;
or delete them entirely from the dataset:
hd(lowIndexes) = [];
or something else?
0 个评论
Astrid
2012-4-8
1 个评论
Andrei Bobrov
2012-4-10
Hi Astrid!
This is the same as:
ix = find(t(t2));
ix(:,end+1) = ix + 1;
id = t2(ix);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!