How to create a matrix using nested for loops

2 visualizzazioni (ultimi 30 giorni)
jesus escareno
jesus escareno il 5 Feb 2016
Modificato: Stephen23 il 7 Feb 2016
t=linspace(0,2,100);
x=linspace(0,1,50);
n=linspace(1,5,5000);
sum=0;
for x1=0:50
for t1=0:100
for n1=1:5000
sum(x1,t1,n1)= sum(x1,t1,n1) + x.^n/factorial(n)+ t.^n/(50*factorial(n));
end
end
end
This is my code. Essential I'm trying to create a matrix of the solutions to the sum so I can later use the functions surf. However once I run the code I get "Subscript indices must either be real positive integers or logicals." What I'm doing wrong and can be done to fix my code? Thank you.
  1 Commento
Stephen23
Stephen23 il 6 Feb 2016
Modificato: Stephen23 il 7 Feb 2016
@jesus escareno: you should NOT call any variable sum, as this is the name of an extremely important inbuilt function sum. When you define your variable with the same name ("shadowing" the inbuilt fucntion) it will stop lots of code from working. DO NOT USE SUM as a variable name!

Accedi per commentare.

Risposte (1)

Star Strider
Star Strider il 5 Feb 2016
The problem, simply, are:
for x1=0:50
for t1=0:100
Zero is not a positive integer. In MATLAB, all indices and index references begin with 1. If you want to use the indices with zero values in your calculations, subtract 1 from the index values, but always define indices that are positive integers (integers greater than or equal to 1).
  2 Commenti
jesus escareno
jesus escareno il 6 Feb 2016
yea that took care of that problem......but I'm getting Matrix dimensions must agree.
Star Strider
Star Strider il 6 Feb 2016
First call your variable something other than ‘sum’ since that is the name of a (very important) built-in MATLAB function, and it will cause problems for you if you later want to use it in your code. This is called ‘overshadowing’, and is to be avoided at all costs!
Second You have created ‘t’, ‘x’ and ‘n’ as vectors, so you have to refer to them element-wise (that is to say element-by-element) in your loop calculation as you have defined it. Referring to them as vectors (although correct MATLAB syntax when using vectorised calculations), will cause the errors you are getting when you specify element-by-element calculations as you do in your code. You need to subscript each of them appropriately for your code to work.
I am not certain what you are doing, but there is nothing inherently wrong with your code as you have written it, other than using ‘sum’ as a variable name. You simply have to do element-wise addressing for your variables, and it should create the 3D matrix you want.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by