MATLAB Matlab, for loop simple division problem

AI Thread Summary
The discussion revolves around a script intended to calculate values based on an array 'u' but initially produces incorrect results. The user expected the output to be a specific array but received unexpected values due to a misunderstanding of indexing in MATLAB. The key issue identified is that the variable 'i' contains multiple elements, leading to incorrect indexing of 'u'. A solution is provided, suggesting that variables should be initialized outside the loop and correcting the loop structure to ensure proper indexing. The revised code successfully generates the expected output. Additionally, a minor note about parentheses was mentioned in the edit.
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

Back
Top