how to use for loops command to ignore 10 times the same code?

1 次查看(过去 30 天)
Hi all
I am writing code and getting result. But my code is too long, I am just repeating the same code 10 times to get 10 curves and average of the 10 curves.
Is there any way to make shorter my code?
Thanks a lot!
  2 个评论
Stephen23
Stephen23 2016-9-13
This is easy: don't use numbered variables, instead use one variable, indexing and a loop.
Learn to keep data together which makes the code simpler and faster. If you had put that data together into one array then you could have used vectorized code:
For whatever reasons some beginners love copy-and-pasting code: but computers are great at brainlessly repeating a simple task, so why do those beginners want to do the computer's brainless task? Not only is this a waste of time, it also increase the chances of bugs because more code -> more bugs, and it is much harder to check many repeated blocks of similar code. Much better is to write that code once inside a loop, and get the computer to repeat it. This requires using indexing, of course, within the loop.
Or write the code in function, and call that function repeatedly.
Numbered variables are an indicator of bad code design: this is usually an attempt to include meta-data in the variable names, whereas the best way to deal with meta-data is to realize that it is data, and store it somehow as data. At the very least, indexing and the dimensions of arrays can be used to indicate meta-data (with dimensions corresponding to test cases, samples, etc).
Numbered variables also invariably lead to bad design decisions that require slow and buggy code:
You should also avoid putting in useless code like this:
for iii=1:length(TXT);
date_str(iii,:)=TXT(iii,1);
end
Why bother using a loop? Much simpler is to just allocate the whole column:
date_str = TXT(:,1);
Read this for more good MATLAB coding practices that all beginners should learn:

请先登录,再进行评论。

采纳的回答

Andrei Bobrov
Andrei Bobrov 2016-9-13
编辑:Andrei Bobrov 2016-9-13
[NUMERIC,TXT]=xlsread('whole10L22.xlsx');
x= NUMERIC(:,1);
y = NUMERIC(:,2);
Mag = NUMERIC(:,3);
date_num = datenum(TXT,'dd.mm.yy');
date1=datenum('01/01/1962','dd/mm/yyyy');
date2=datenum('01/01/2016','dd/mm/yyyy');
A=-0.59;
B=43.45;
L=0.09;
x11=A-L;
x22=A+L;
y11=B-L;
y22=B+L;
t = x > x11 & x < x22 & y > y11 & y < y22 &...
date_num > date1 & date_num < date2;
s = [numel(Mag),10];
[~,ii] = sort(rand(s));
Mag1 = Mag(ii);
condition = bsxfun(@and,Mag1 >= 2.5, t);
Distance = datenum(1960+(0:3:18*3)',7,1);
b = histc(bsxfun(@times,date_num,condition),Distance);
plot(Distance,b,'r','LineWidth',1);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by