My 'for' loops aren't altering anything except a few points in my matrices

I'm writing a finite difference problem for my heat transport class. I'm not the best at coding but I feel like my code should work. The code runs but doesn't work. The code doesn't seem to change all the nodes in the array, only the corners? If anyone has any tips I would greatly appreciate it. I attached my code and it can be viewed below. cookie(i,j,k) should change each time the conditions are met and then it should iterate every time step. cookie(i,j,k) is an array with k pages of i by j arrays ( or it should be).

1 Comment

Well i got it running by chaning the conditions of the elseif's to be separate statements but it seems to be killing the overarching while loop before the conditions I want are met?

Sign in to comment.

 Accepted Answer

Problem: it is very simple: you are using a syntax that does not do what you think it does.
This syntax
n_B > i > 1
is actually exactly equivalent to this (because > is a binary operator and because of simple left-to-right operator precedence):
(n_B > i) > 1
which of course will always be false, because it is equivalent to either of these:
(true) > 1
(false) > 1
MATLAB does NOT have any ternary operators for any logical equivalence operators. When you read the documentation you will find binary operators, e.g. >, <, ==, etc. but no ternary operators, so that was a syntax that you just invented without reading the MATLAB documentation.
Solution: you will have to change all of your logical operations to this syntax:
(n_B > i) && (i > 1)
PS: rather than using loops and if's and copy-and-paste, most of that code looks like it could be vectorized quite easily.

2 Comments

Thank you so much! That worked perfectly. I'm definitely not very familiar with Matlab. I'm a chemical engineer and only had a 6 week crash course in it. What do you mean by vectorizing? I'm sure my code isn't very efficient but it's the only way that made sense to me....
@Joshua Wiseman: I hope that it helped.
Vectorized code is a way of writing code using matrices and vectors to avoid loops and if's. It is often a very compact and efficient way to manipulate numeric data.
Like anything it takes time and practice to get used to.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2013a

Community Treasure Hunt

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

Start Hunting!