How to I add loop vector iteration values to one big matrix?
1 view (last 30 days)
Show older comments
I have a loop that iterates a function 6 times, each time it produces a matrix. How do I add each iteration to a single matrix in a new column? I should see a 6x6 matrix at the end of the loop.
I would like X matrix to have all 6 rows answers. A single iteration of this function will provide an answer that will look similar to this:
2904.5 3019.3 3065.7 3070.6 3044.3 2996.1
The loop code:
for phi=0.5:0.2:1.5
X=Function(3000,1,phi)
end
The code above just replaces each iteration so I just see one line.
I tried to use something along the lines the code below, but it will not work, or will add everything to one row. (one other function would work if the answer is one variable, but will not work if there are multiple variables in one row)
it = it+1
X(it)=Function(3000,1,phi)
Thanks again!
4 Comments
Stephen23
on 6 Oct 2018
"The output will be a 1x5 matrix"
but in your question you show a 1x6 vector. Which is correct?
Accepted Answer
Stephen23
on 6 Oct 2018
Edited: Stephen23
on 6 Oct 2018
Assuming that myfun outputs a 5-element vector, just use indexing like this:
phi = 0.5:0.2:1.5;
mat = nan(5,numel(phi));
for k = 1:numel(phi)
mat(:,k) = myfun(3000,1,phi(k));
end
This puts each result as one column of mat, which makes plotting easier. Or you could swap the dimensions of mat to put the results as rows. Whatever works for you.
2 Comments
Stephen23
on 7 Oct 2018
Edited: Stephen23
on 7 Oct 2018
"It spits out the following error:"
That is a warning, not an error.
"any ideas?"
The algorithm is producing numeric garbage for your input data, and this is unrelated to your original question.
The problem is caused by a combination of your input data (which you have not given us) and the function Gibbs (which you have not given us, or shown us where you got it from) that results in some calculation (inside Gibbs) being performed that returns numeric garbage. But without the complete error message (i.e. all of the red text) and the input data and the function then debugging your code means debugging by guessing, which is not a very efficient way to debug code.
Solution: use different data, or try a different algorithm, or learn that not all problems are numerically solvable using naive implementations of some algorithm.
Search this forum for "Matrix is close to singular or badly scaled" and you will get many discussions on this topic, with very good and detailed explanations. Go and read them.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!