I have a question about how can I use different values in each iteration with a loop. I have an image with 145 bands. I calculate the size, the number of rows, columns and bands
size=size(HYP);
nrow= size(1);
ncolu= size(2);
nbands= size(3);
I have to do an operation for every band, and then obtain the result but I don't know how to change one of the values automatically for every iteration. I'm going to try to simplify the question. This is my loop. The value rad1 is defined before. I need that on every loop uses some value defined before (for example, band2 value rad2, band3 rad3...) and extract a result for each one (nd1 changes automatically to nd2, etc.)
output= zeros(nrow,ncolu,nbands);
for banda=1:nbands;
nd1= -((3.141592*rad1)/-HYP2(:,:,1));
output(banda,1)= (nd1);
end
end
So, for the first iteration:
nd1= -((3.141592*rad1)/-HYP2(:,:,1));
output(banda,1)= (nd1);
for the second...
nd2= -((3.141592*rad2)/-HYP2(:,:,2));
output(banda,2)= (nd2);
Rad1,rad 2... rad145 etc is defined before. And at the end, output would be a 145 band matrix.
Do you know how can I do it? Really thanks in advance,
Don't try using different variable names. Just use rad(1), rad(2) etc. and then
output= zeros(nrow, ncolu, nbands);
for banda=1:nbands;
output(:,:,banda) = -((3.141592*rad(banda))/-HYP2(:,:,1));
end
(Your initialization of output doesn't match the code in your loop, by the way.)
Related
With rng() before for loop Matlab generate one array of random number, within for loop another one. Both results are repeatable, so rng() seeds work. But I want to know the reason of such behavior.I was expecting the results to be same. I think actually it is not because of rng but for loop
Code exapmle?
for i = 1:2
rng(1,'philox');
disp(randn(2,1)); % 1st number is 0.0906, 2nd one is -0.7327
end
rng(1,'philox');
for i = 1:2
disp(randn(2,1)); % 1st number is 0.7565, 2nd one is -0.7096
end
Shouldn't the results be same? Isn't rng(1,..) storing same array of numbers for seed 1
Your code works as you expect and would describe, I believe. You are definitely not showing in your code example all the outputs. This is what I get when running it.
>> test
First case:
0.0906
-0.7327
0.0906
-0.7327
Second case:
0.0906
-0.7327
0.7565
-0.7096
In the first case, you reset the random number generator inside the loop, and there fore you get twice the same results (two numbers). In the second case, you only set it once, and therefore you get the same numbers as before, and then the second loop you get the next 2 corresponding random numbers produced by the algorithm. These algorithms, once started, will produce an infinite amount of different numbers, and they won't produce the same unless you explicitly call the restart of the algorithm with the seed, like you do in the first example.
All this is way less confusing if you call disp(randn(1)) inside the loop, instead of generating 2 numbers each time.
I am a beginner in Matlab and have not been able to find an answer to my question so far. Your help will definitely be very much appreciated.
I have 70 matrices (100x100), named SUBJ_1, SUBJ_2 etc. I would like to create a loop so that I would calculate some metrics (i.e. max and min values) for each matrix, and save the output in a 70x2 result matrix (where each row would correspond to the consecutively named SUBJ_ matrix).
I am struggling with both stages - how to use the names of individual variables in a 'for' loop and how to properly save individual outputs in a combined array.
Many thanks and all the best!
Don't use such variable names, create a big cell array named SUBJ and put each Matrix in it.
r=zeros(numel(SUBJ),2)
for idx=1:numel(SUBJ)
r(idx,1)=min(min(SUBJ{idx}))
r(idx,2)=max(max(SUBJ{idx}))
end
min and max are called twice because first call creates maximum among rows, second call among columns.
Even though this is in principle possible in Matlab, I would not recommend it: too slow and cumbersome to implement.
You could instead use a 3-D matrix (100x100x70) SUBJ which would contain all the SUBJ_1 etc. in one matrix. This would allow you to calculate min/max etc. with just one line of code. Matlab will take care of the loops internally:
OUTPUT(:,1) = min(min(SUBJ,[],1)[],2);
OUTPUT(:,2) = max(max(SUBJ,[],1)[],2);
Like this, OUTPUT(1,1) contains min(min(SUBJ(:,:,1))) and so on...
As to how to use the names of individual variables in a 'for' loop, here gives an example:
SUBJ = [];
for idx = 1:70
term = eval(['SUBJ_',num2str(idx)]);
SUBJ = [SUBJ; max(max(term)),min(min(term))];
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.
i want fsolve to calculate the output for different uc each time (increasing uc by 0.001 each time). each output from fsolve should be sent to a simulink model seperatly. so i set a loop to do so, but i believe that at the currenty constellation (if it will work)will just calculate 1000 different values? is there a way to send out the values seperately?
if not, how can i create a parameter uc. that goes from 0 to say 1000? i tried uc=0:0.001:1000, but again, the demension doen't seem to fit.
how do i create a function that takes the next element of a vector/matrix each time the function is called?
best regards
The general approach to iterating over an array of values and feeding them one-by-one into a series of evaluations of a function follows this form:
for ix = 0:0.1:10
func(arg1, arg2, ix)
end
See how each call to func includes the current value of ix ? On the first iteration ix==0, on the next ix==0.1 and so forth. You should be able to adapt this to your needs; in your code the loop index (which you call i) is not used inside the loop.
Now some un-asked-for criticism of your code. The lines
x0=[1,1,1];
y=x0(1);
u=x0(2);
yc=x0(3);
options=optimset('Display','off');
do not change as the loop iterations advance; they always return the same values whatever the value of the loop iterator (i in your code) may be. It is pointless including them inside the loop.
Leaving them inside the loop may even be a waste of a lot of time if Matlab decides to calculate them at every iteration. I'm not sure what Matlab does in this case, it may be smart enough to figure out that these values don't change at each iteration, but even if it does it is bad programming practice to write your code this way; lift constant expressions such as these out of loops.
It's not clear from the fragment you've posted why you have defined y, u and yc at all, they're not used anywhere; perhaps they're used in other parts of your program.
I am trying to use MATLAB in order to generate a variable whose elements are either 0 or 1. I want to define this variable using some kind of concatenation (equivalent of Java string append) so that I can add as many 0's and 1's according to some upper limit.
I can only think of using a for loop to append values to an existing variable. Something like
variable=1;
for i=1:N
if ( i%2==0)
variable = variable.append('0')
else
variable = variable.append('1')
i=i+1;
end
Is there a better way to do this?
In MATLAB, you can almost always avoid a loop by treating arrays in a vectorized way.
The result of pseudo-code you provided can be obtained in a single line as:
variable = mod((1:N),2);
The above line generates a row vector [1,2,...,N] (with the code (1:N), use (1:N)' if you need a column vector) and the mod function (as most MATLAB functions) is applied to each element when it receives an array.
That's not valid Matlab code:
The % indicates the start of a comment, hence introducing a syntax error.
There is no append method (at least not for arrays).
Theres no need to increment the index in a for loop.
Aside of that it's a bad idea to have Matlab "grow" variables, as memory needs to be reallocated at each time, slowing it down considerably. The correct approach is:
variable=zeros(N,1);
for i=1:N
variable(i)=mod(i,2);
end
If you really do want to grow variables (some times it is inevitable) you can use this:
variable=[variable;1];
Use ; for appending rows, use , for appending columns (does the same as vertcat and horzcat). Use cat if you have more than 2 dimensions in your array.