This question already has answers here:
MATLAB, how to change loop index inside for loops [duplicate]
(2 answers)
Change for loop index variable inside the loop
(4 answers)
Closed 1 year ago.
I am triying to write a code which automatically checks the input data with a bounded range and removes the ones outside this boundary. I have written the following code:
LANDA_E_4=landa;
for i=1:m
if i>m
break
elseif LANDA_T_2(i)<0.2021e+03 || LANDA_T_2(i)>1.3317e+03
LANDA_T_2(i)=[];
i=i-1;
end
The problem here is that the "i" does not update within the loop. Consider the first element is not within the range, so it gets removed. now the loop should check the new first element which is the previous second element (before removing the first one) but the "i" whitin the loop is still 2. I can't update "i".
Thank you in advance
The problem with your approach is that at each iteration of the loop i gets set to the number of that iteration, even if you modify it in between. (And besides taht it is bad practice to use i as a variable, as by default it is set to the imaginar unit 1i.) To make your approach work you would have to use a while loop.
But it is even easier to use logical indexing instead and avoid loops like so:
% bougs data
m = 100;
LANDA_T_2=rand(1, m)*2e3;
% remove loops
LANDA_T_2(LANDA_T_2<0.2021e+03 | LANDA_T_2>1.3317e+03) = [];
disp(size(LANDA_T_2))
Try it online!
Related
This question already has an answer here:
parfor doesn't consider information about vectors which are used in it
(1 answer)
Closed 5 years ago.
I want to parallelize some part of my code in matlab. for example below part:
v1=[1,3,6,8];
ggx=5.*ones(15,14);
gax=ones(15,14);
parfor i = 1:length(v1)
m = v1(i);
if m > 1
gax(1:m-1,m-1) = ggx(1:m-1,m-1);
end
if m<nn
gax(m+1:end,m) = ggx(m+1:end,m);
end
end
But there is an error:
Error: The variable gax in a parfor cannot be classified.See Parallel for Loops in MATLAB, "Overview".
Do anyone knows how can I remove the error? Other useful information is that v1 is an increasing vector which doesn't contain any repeated element.
As mentioned in the error message, you must follow the Sliced Variable rule.
Both gax and gay breaks rules of Fixed Index Listing and Form of Indexing. Also, you can this example A(i,20:30,end) % 20:30 not scalar as an example of not sliced variables in the document.
Therefore, you should change the all part of the parfor to getting a proper parallel computation. In the other words, you must design a proper parallel algorithm which you can parallelized the method, based on the loop variable.
Type of First-Level Indexing — The first level of indexing is either parentheses, (), or braces, {}.
Fixed Index Listing — Within the first-level parentheses or braces, the list of indices is the same for all occurrences of a given variable.
Form of Indexing — Within the list of indices for the variable, exactly one index involves the loop variable.
Shape of Array — The array maintains a constant shape. In assigning to a sliced variable, the right side of the assignment cannot be [] or '', because these operators attempt to delete elements.
This question already has answers here:
Save loop data in vector
(2 answers)
Closed 7 years ago.
I want to save the following for-loop results in a new matrix using Matlab, how can I do that or any other suggestions?
Where X is a 5467-by-513 matrix , id is a 143-by-1 vector and wkno is a 44-by-1 vector
for i=1:size(id,1);
for j=1:size(wkno,1);
tst= X(:,1)==id(i) & X(:,2)==wkno(j);
M=mean(X(tst,:));
end
end
Just make sure you actually save the things to a matrix instead of a scalar-variable, i.e. add the subscript indices to the variable you're saving to:
for ii=1:size(id,1);
for jj=1:size(wkno,1);
tst(ii,jj)= X(:,1)==id(ii,1) & X(:,2)==wkno(jj,1);
M(ii,jj)=mean(X(tst,:));
end
end
Not that I refrained from using i and j as a variable, since this is a bad idea. I added the ,1 to id and wkno, to make sure you use them as column variables. This is a good habit to get into, because single indices will go wrong when you have a multi-dimensional array.
This question already has answers here:
How do I get the index of the smallest element in an array in matlab?
(2 answers)
Closed 8 years ago.
I want to match a time to the minimum value of TEMP found in an array that I'm reading into a struct from a netcdf file in a loop (that's doing a lot more stuff - no I don't want to get rid of the loop). I have the snctools so that's what I'm using for netcdfs.
Here's my current relevant lines of code:
%Get the netcdf file with file_string loading into MATLAB
nc=netcdf(file_string);
%Work out the number of files I need to loop through
[files]=dir('*.nc');
max1=length(files);
for d1=1:max1
%extract the TEMP 1-D array
B1=nc{'TEMP'}(:)
%assign to value
dat.TEMP_min(d1)= min(B1);
end
Now there is another variable of the same length called 'TIMES'. If min(B1)=10.5 and is the nth element of B1 then I want to locate the nth element of TIMES and save it as dat.TEMP_min_TIME. How would I go about this?
Please provide enough notes on any code so that a novice can understand it.
You can just use inside your loop (sorry for pseudocode, not sure about your definitions of n and TIMES)
[M,I] = min(B1);
dat.TEMP_min(d1)= M;
if (I == n)
dat.TEMP_min_TIME = nc1{'TIMES'}(I); %
end
Why does the following code
for a=1:5:100
a = a+ 1;
end
iterate 20 times?
a goes up by 5 every iteration, but also goes up by 1 in the actual loop. 99/6 = 16.5 or 17 iterations, so why does it do 20?
Thanks for any help understanding how the for loop function works.
In Matlab, whatever you do to the loop index variable (a) inside a for loop is thrown away, and a gets reset at the beginning of the next pass. So the a = a + 1 inside the loop has no effect. See Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?.
Unlike languages like C or C++, changing the loop index in MATLAB is not persistent across loop iterations.
In other words, if you increment a, it will remain incremented for the rest of that loop. However, upon reaching the top of the loop, MATLAB does not add 5 to a. Instead, it selects the next value of a from the list of values you provided. This effectively "overwrites" the change that you made to the loop index inside the loop.
The way to view a for loop in MATLAB like this one,
for a=1:5:100
Is to provide an array directly,
ai = [1:5:100];
for a = ai
The loop will iterate over the values in ai. Period. It doesn't matter what you do to a in the loop. At the beginning of each iteration, the value of a gets set according to the array given to the for statement.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Matlab - building an array while looping
Matrix of unknown length in MATLAB?
How do you put all of the "a" values together to form a vector?
for i=1:3
a=2+i
end
Also this is maybe a style question but when do you put a semicolon after the end in a for loop such as the one above, also is it proper to put a semicolon after the first line?
You need to index into a, like this:
for ii=1:3
a(ii) = 2+ii;
end
I prefer to use ii as a loop variable to avoid clashing with MATLAB's built-in i. You should also pre-allocate a if you know the size before the start of the loop, like so:
N = 100;
a = zeros(1,N);
for ii=1:N
a(ii) = 2 + ii;
end
Personally, I never put any punctuation after the for ii=1:3 part, except when writing a one-liner FOR loop, like so:
for ii=1:N, a(ii) = 2 + ii; end
Note that you can construct this more efficiently as such:
a=1:3;
a=a+2;
The first line assigns a to be the vector (1,2,3), the 2nd line adds 2 to every element.
"Efficiency" doesn't matter much in such a small vector, but in general you'll get much better mileage out of matlab if you get used to thinking more like this.