Updating values with for-loop

Hello everyone,
I want to update the matrix "e" according to the new value of matrix "d" for each iteration.
Matrix "d" is generated in each iteration according to the new maximum value if matrix "f"
clear all
clc
d = zeros(2,4);
a = [2 2;1 1;4 1;1 1;4 2;1 1;3 2;3 1;2 1;1 2];
b= [0 0 0 0;0 1 0 0;1 0 0 0;0 0 0 0;0 0 0 1;0 0 0 0;1 0 0 0;0 0 0 0;0 0 0 0;0 0 0 1;1 0 0 0;0 0 0 0;0 0 0 0;0 0 1 0;0 0 1 0;0 0 0 0;0 1 0 0;0 0 0 0;0 0 0 0;1 0 0 0];

 Accepted Answer

Mohammad - Please edit your above code so that it is a little more readable. Comments would definitely help. Please also describe the problem you are facing with the above - why isn't it doing what you want it to do? What is it supposed to do?
Some things that I noted:
The condition on your first if statement is invalid: the matrix e is not yet defined so will error out with the Undefined function or variable e. As well, what is the intent of that condition in trying to check to see if a matrix is greater than or equal to zero? Are you checking to see if all elements in it are greater than or equal to zero (and why?)?
It may be a good idea to put a breakpoint in the code - at the first line - and then step through the code to see if what is happening (at each line) is exactly what you want. For example, a matrix b is defined but unused - why? The matrix c is a 2x4 matrix then on the next line is set to zero which will cause a division by zero problem at the line
f = (e.^2)./c;
and so f is a 2x4 matrix of NaN values. The matrix a is 10x2 and yet the code
for j = 2:size(a,3)+1
is trying to get the size of third dimension (which doesn't exist!), returning the value of one. Why?
What problem is the above code trying to solve? It may be a good idea to comment the code so that it is clear to all what the intent of each line is.

3 Comments

Hi Mohammad - the above code still fails; I strongly suggest that before posting new code, you test it out to make sure that it actually runs to completion. The offending line is:
n(:,:,j) = n(:,:,j-1) + v(:,:,j-1);
because v is a two dimensional matrix only, but the above code treats it as if has three dimensions.
Debugging with MATLAB is incredibly easy. I urge you to step through each line of code (especially since there are so few lines) and at each line ask yourself, "does this make sense?" or "does this solve the problem?". If you have any specific questions about the syntax, then by all means ask away!
Thanks Geoff, I've checked line by line and solved all errors.

Sign in to comment.

More Answers (0)

Categories

Asked:

Moe
on 4 May 2014

Edited:

Moe
on 6 May 2014

Community Treasure Hunt

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

Start Hunting!