Matlab, for loop simple division problem

  • Context: MATLAB 
  • Thread starter Thread starter feicobain
  • Start date Start date
  • Tags Tags
    Division Loop Matlab
Click For Summary
SUMMARY

The forum discussion addresses a MATLAB script issue related to a for loop performing division. The original code incorrectly initializes the variable X within the loop and misuses indexing, leading to incorrect results. The corrected code initializes X outside the loop and uses proper indexing, resulting in the expected output of X = [10; 5]. The importance of correct variable initialization and indexing in MATLAB is emphasized.

PREREQUISITES
  • Basic understanding of MATLAB syntax and operations
  • Familiarity with for loops in programming
  • Knowledge of matrix indexing in MATLAB
  • Concept of variable initialization in programming
NEXT STEPS
  • Review MATLAB for loop syntax and best practices
  • Learn about matrix indexing and manipulation in MATLAB
  • Explore variable initialization techniques in MATLAB
  • Investigate debugging methods for MATLAB scripts
USEFUL FOR

This discussion is beneficial for MATLAB users, particularly beginners and intermediate programmers, who are looking to improve their understanding of for loops, variable initialization, and indexing in MATLAB.

feicobain
Messages
4
Reaction score
0
I put down a script like this

for u=(10:10:20)'
i=(1:size(u,1))'
X=zeros(size(u,1),1)
X(i,1)=100/u(i,1)
end

I expect to get a result like

X=
10
5

but it came out like

X=
0
5

It seems it does work if it contain / in the equation. Please help!
 
Physics news on Phys.org
Did you realize that i contains two elements? The syntax u(i,1) makes no sense when i contains two elements. You've either got u and i jumbled up, or I'm not understanding what you're trying to do.

You also need to initialize your variables outside the loop.

So, this is probably the code you're looking for:

Code:
u=(10:10:20)'
X=zeros(size(u,1), 1)

for i = 1:size(u,1)
X(i,1) = 100 / u(i,1)
end

Which produces the desired results.

EDIT: Ooops, forgot some parentheses...
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 32 ·
2
Replies
32
Views
4K
  • · Replies 1 ·
Replies
1
Views
3K
Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
8K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 3 ·
Replies
3
Views
5K