Need help with taking an array inside a for loop and plotting it

Asked by Ryan O'Shea

Ryan O'Shea (view profile)

on 12 Sep 2019
Latest activity Commented on by Ryan O'Shea

Ryan O'Shea (view profile)

on 12 Sep 2019
Accepted Answer by David Hill

David Hill (view profile)

I believe I have been able to get it so the A values and Gamma values are all correct. However, when I graph the Comp vector vs A1, it only plots the last A1 value across the entire Comp vector. How can i alter this so it displays each A1 value vs. the Comp vector

Tags

Answer by David Hill

David Hill (view profile)

on 12 Sep 2019

A1=exp((Om*(1-Comp).^2./(R*T1)).*Comp);
A2=exp((Om*(1-Comp).^2./(R*T2)).*Comp);
plot(Comp,A1)
hold on
plot(Comp,A2)
Get rid of the loops.

Answer by Walter Roberson

Walter Roberson (view profile)

on 12 Sep 2019

You are not storing the values as they are generated.
There is a pattern you should learn:
vector_of_values = some_vector %like 0:.1:1 for example
number_of_values = length(vector_of_values);
results = zeros(1, number_of_values);
for index = 1 : number_of_values
this_particular_value = vector_of_values(index);
compute something using this_particular_value
results(index) = result of computation
end
plot(vector_of_values, results)
When you use this pattern, the vector of values can include anything suitable, in any order. For example, it could be
vector_of_values = [pi, -exp(1), 5.7-1.3i, -exp(1)]
This example shows that the values do not have to be sorted, do not have to be positive integers, do not have to be real-valued, do not have to be unique. This is a general pattern that can be used no matter how messy the vector of values is.
Notice that since you computed the vector of values ahead of time, the full list of values is available to plot() against later.
There is also a simplified version of this that can be used in some cases:
results = zeros(1, last_integer); e.g., zeros(1,8)
for index = 1 : last_integer %e.g., for index = 1:8
compute something using index as the value to compute with, e.g., primes(index)
results(index) = result of computation
end
plot(1:last_integer, results) %notice you end up rebuilding the list of values
There are variations on this for the case where the values are consecutive integers but not starting from 1, but they becomes less clear.

Ryan O'Shea

on 12 Sep 2019
Thank you!