Can any body help me explain Line 7 of this code. What does this line
temp(min(temp,[],2) >=1 & max(temp,[],2)<=N,:)
do in the code?
Line 7 of this code is throwing me off
N=10;
H=-1;
J=0;
for i=1:N
for j=1:N
temp=[i-1,j;i+1,j;i,j-1;i,j+1];
ngh{i,j}=temp(min(temp,[],2) >=1 & max(temp,[],2)<=N,:);
end
end
That line is selecting the rows of temp which have all values between 1 and N, and assigning that submatrix to ngh{i,j}.
Note that
min(...,[],2) or max(...,[],2) gives the minimum or maximum of each row;
The logical comparison with 1 or N and the & operation result in a logical index vector, which is used to address the desired rows of temp (and all columns).
Related
I'm a total beginner when it comes to MATLAB, so I have a question for this. How am I supposed to write this code out and if by any chance, can someone be kind enough to write out the code because I've been struggling with this. Use loops to create 3 x 5 matrix in which the value of each element is half of its row number plus three times its column number. for instance, the value of element (2,5) is: 1/22+35
The nested loops control the indexing of the matrix. The outer for-loop traverses through the rows of the matrix and the inner for-loop traverses through the columns of the matrix.
The second part of this question requires using a combination of the looping/scanning variables Row and Column to set the value of the matrix:
Matrix Value = (Row ÷ 2) + (3 × Column)
Number_Of_Rows = 3;
Number_Of_Columns = 5;
Matrix = zeros(Number_Of_Rows,Number_Of_Columns);
%Running through the array indices using two loops%
for Row = 1: Number_Of_Rows
for Column = 1: Number_Of_Columns
%Evaluating the value based on the current row and column index%
Matrix(Row,Column) = (Row/2) + (3*Column);
end
end
Matrix
Result:
Looping Methodology:
Variable Matrix Opened In Workspace:
Here's an intuitive way to do this:
% Initialize row num and column num
row = 3;
column = 5;
% H is the matrix of desire
% Initialize it as a 3*5 zero matrix
H = zeros(3,5);
% Outer loop, over column index
% Remember Matlab's index start with 1 not 0
for c = 1:column
% Inner Loop, over row index
for r = 1:row
% The algorithm of each element in the matrix
H(r,c) = 0.5*r+3*c;
end
end
I have a 64 X 64 matrix that I need to find the column-wise mean values for.
However, instead of dividing by the total number of elements in each column (i.e. 64), I need to divide by the total number of non-zeros in the matrix.
I managed to get it to work for a single column as shown below. For reference, the function that generates my matrix is titled fmu2(i,j).
q = 0;
for i = 1:64
if fmu2(i,1) ~= 0;
q = q + 1;
end
end
for i = 1:64
mv = (1/q).*sum(fmu2(i,1));
end
This works for generating the "mean" value of the first column. However, I'm having trouble looping this procedure so that I will get the mean for each column. I tried doing a nested for loop, but it just calculated the mean for the entire 64 X 64 matrix instead of one column at a time. Here's what I tried:
q = 0;
for i = 1:64
for j = 1:64
if fmu2(i,j) ~= 0;
q = q +1;
end
end
end
for i = 1:64
for j = 1:64
mv = (1/q).*sum(fmu2(i,j));
end
end
Like I said, this just gave me one value for the entire matrix instead of 64 individual "means" for each column. Any help would be appreciated.
For one thing, do not call the function that generates your matrix in each iteration of a loop. This is extremely inefficient and will cause major problems if your function is complex enough to have side effects. Store the return value in a variable once, and refer to that variable from then on.
Secondly, you do not need any loops here at all. The total number of nonzeros is given by the nnz function (short for number of non-zeros). The sum function accepts an optional dimension argument, so you can just tell it to sum along the columns instead of along the rows or the whole matrix.
m = fmu2(i,1)
averages = sum(m, 1) / nnz(m)
averages will be a 64-element array with an average for each column, since sum(m, 1) is a 64 element sum along each column and nnz(m) is a scalar.
One of the great things about MATLAB is that it provides vectorized implementations of just about everything. If you do it right, you should almost never have to use an explicit loop to do any mathematical operations at all.
If you want the column-wise mean of non-zero elements you can do the following
m = randi([0,5], 5, 5); % some data
avg = sum(m,1) ./ sum(m~=0,1);
This is a column-wise sum of values, divided by the column-wise number of elements not equal to 0. The result is a row vector where each element is the average of the corresponding column in m.
Note this is very flexible, you could use any condition in place of ~=0.
for i = 1:6
if data(i,1) == 1
disp(i)
m(i,:) = data(i,:)
end
end
The code above returns a matrix m, with rows of data from the data file.
However, data(i,1) == 1 is true 4 times for the particular data, however m has 6 rows. 2 of the rows of m are just full of 0's, but the if statement is only true 4 times.
Why is that happening?
In answer to "why is that happening", it is because your matrices are the same size, but you only assign values to the rows which satisfy a condition. Therefore leaving other rows as 0s.
You either need a way to build m row by row (see end of this post) or create it in another way (my answer).
You can do this with logical indexing
% For creating m
m = data(data(:, 1) == 1, :);
% For displaying which indices satisfy your condition, one call to disp
disp( find(data(:, 1) == 1) )
Breaking this down, m is assigned to the values of data, where the column 1 of data is equal to 1, and all of the columns.
find returns the index of any non-zero element. The logical indexing returns an array of 0s and 1s, so all elements which satisfy the condition (and are 1) will be indexed by find.
You could also create the logical index and use it twice, better for maintenance at a later date if your condition changes:
% create logical index
idx = ( data(:,1) == 1 );
% same as above but using idx
m = data(idx, :);
disp( find(idx) )
Documentation
Logical indexing - https://uk.mathworks.com/help/matlab/matlab_prog/find-array-elements-that-meet-a-condition.html
find - https://uk.mathworks.com/help/matlab/ref/find.html
#Ander's suggestion to append only certain rows will work, and demonstrates well how to build a matrix. However, in this case you do not need your loop and if condition at all.
This is standard MATLAB.
Lets assume data(1,1) and data(3,1) are 1.
Then m(1,:)=data(1,:) and later m(3,:)=data(3,:). But what about m(2,:) It has to exist, because you filled m(3,:). There is no 3 without 2!
If you want m to have only the ones where data(i,1) == 1 then do:
m=[]; %create empty matrix
for i = 1:6
if data(i,1) == 1
disp(i)
m= [m; data(i,:)]; % "append" to m
end
end
I am trying to build a submatrix by iterating on the rows of the last column in the main matrix which is of size (50000, 21), and if the value inside is greater than 1000 then the whole corresponding y(i,:) row will be added to the new submatrix and add to it more 33 consecutive rows from the main matrix.
I wrote this code below but it is returning only a 33x21 size and I think i am iterating through the j index but not the i index:
for i=1:50000
if y(i,21)>1000
for j=1:33
n(j,:)=y(j+i,:)
j=j+1
end
i=i+1
end
end
What am I doing wrong?
try this:
k=1;
for i=1:50000
if y(i,21)>1000
for j=0:33 %watch this out i am not sure how many rows you want to keep and if these involve the one with the last element greater than 1000 or not..%
n(k,:)=y(j+i,:);
j=j+1;
k=k+1;
end
i=i+1;
end
end
Problem is that every new set of 33 rows overwrites the previous one.The above code i think will do the trick.
this is a vectorized verison that needs no loop:
%find elements that are greater than 1000
lo = find(y(:,21) > 1000);
%indeices of 33th row after the lo,
%since it may take a value that is greater than the size of matrix we limit this value by min
up = min(size(y,1), lo + 33);
% create indices based on ranges
%see http://stackoverflow.com/a/39434045/6579744
index=cumsum(accumarray(cumsum([1;up(:)-lo(:)+1]),[lo(:);0]-[0;up(:)]-1)+1);
index= index(1:end-1);
n = y(index, :)
This question already has answers here:
Element-wise array replication in Matlab
(7 answers)
Closed 6 years ago.
This is a basic program but since I'm new to MATLAB, I'm not able to figure out the solution.
I have a column vector "Time" in which I want to print value "1" in first 147 cells, followed by "2" in 148 to 2*147 cells and so on. For that, I have written the following script:
Trial>> c=1;
Trial>> k=0;
Trial>> for i = c:146+c
Time(i,1)=1+k;
c=i;
k=k+1;
end
I know I need to iterate the loop over "Time(i,1)=1+k;" before it executes the next statement. I tried using break but that's not supposed to work. Can anyone suggest me the solution to get the desired results?(It was quite simple in C with just the use of curly braces.)
I am sure you don't want to run c=i; in every iteration.
My code should work for you:
x = 10; % Replace 10 by the max number you need in your array.
k = 1;
for i = 1 : x * 147
Time(i, 1) = k;
if rem(i, 147) == 0
k = k + 1;
end
end
This is the prime example of a piece of code that should be vectorized can help you understand vectorization. Your code can be written like this:
n = 147;
reps = 10; %% Replace this by the maximum number you want your matrix to have
Time = reshape(bsxfun(#plus, zeros(n,1), 0:reps), 1, []);
Explanation:
Let A be a column vector (1 column, n rows), and B be a row vector (1 row, m columns.
What bsxfun(#plus, A, B) will do here is to add all elements in A with all elements in B, like this:
A(1)+B(1) A(1)+B(2) A(1)+B(3) ... A(1)+B(m)
A(2)+B(1) A(2)+B(2) ............. A(2)+B(m)
............................................
A(n)+B(1) A(n)+B(2) .............. A(n)+B(m)
Now, for the two vectors we have: zeros(n,1), and 0:reps, this will give us;
0+0 0+1 0+2 0+reps
0+0 0+1 0+2 0+reps
% n rows of this
So, what we need to do now is place each column underneath each other, so that you will have the column with zeros first, then the row with ones, ... and finally the one with reps (147 in your case).
This can be achieved by reshaping the matrix:
reshape(bsxfun(#plus, zeros(n,1), 0:reps), [], 1);
^ ^ ^ ^
| | | Number of rows in the new matrix. When [] is used, the appropriate value will be chosen by Matlab
| | Number of rows in the new matrix
| matrix to reshape
reshape command
Another approach is using kron:
kron(ones(reps+1, 1) * 0:(n-1)
For the record, a review of your code:
You should always preallocate memory for matrices that are created inside loops. In this case you know it will become a matrix of dimensions ((reps+1)*n-by-1). This means you should do Time = zeros((reps+1)*n, 1);. This will speed up your code a lot.
You shouldn't use i and j as variable names in Matlab, as they denote the imaginary unit (sqrt(-1)). You can for instance do: for ii = 1:(n*147) instead.
You don't want c=i inside the loop, when the loop is supposed to go from c to c + 146. That doesn't make much sense.
You can use repmat,
x = 10; % Sequence length (or what ever it can be called)
M = repmat(1:x,147,1); % Replicate array 1:x for 147 columns
M = M(:); % Reshape the matrix so that is becomes a column vector.
I can assume that this is a task to practice for loops, but this will work.
An alternative solution may be to do
n = 147;
reps = 10;
a = ceil( (1:(n*reps)) / n);
You first construct an array with the length you want. Then you divide, and round of upwards. 1 to 147 will then become 1.