Storing calculations into a list

Click For Summary
SUMMARY

The discussion centers on a MATLAB code snippet that computes a value called "numerator" from random selections of two arrays, x and y, each containing 2187 rows. The user expects "numerator" to be stored as a 5x1 array similar to "xval" and "yval," but it is returned as a scalar. The reason for this behavior is clarified: the function nansum applied to a 5x1 array yields a single scalar value, not an array. This highlights the importance of understanding how aggregation functions work in MATLAB.

PREREQUISITES
  • Familiarity with MATLAB programming language
  • Understanding of array operations in MATLAB
  • Knowledge of the nansum function in MATLAB
  • Basic concepts of random number generation in MATLAB
NEXT STEPS
  • Explore MATLAB array manipulation techniques
  • Learn about MATLAB's nansum function and its behavior with different array dimensions
  • Investigate how to store multiple outputs in MATLAB using arrays
  • Study random number generation and selection methods in MATLAB
USEFUL FOR

MATLAB programmers, data analysts, and anyone involved in numerical computations who seeks to understand array handling and aggregation functions in MATLAB.

Tone L
Messages
72
Reaction score
7
I have a code that loops through and does some computation on 5 random values from my lists of data (2187 rows long).

for i = 1:3
randomdata = round(rand(5,1).*2187);

xval = x(randomdata)
yval = y(randomdata)
numerator = length(xval).*nansum(xval.*yval) - (nansum(xval).*nansum(yval))
end

my output on the screen is as follows: 5 random values stored in xval & yval
xval =
3.3
3.2
6.4
4.3
1.2

yval =
13
33
83
42
9

numerator =
-.34
numerator =
-.12
numerator =
-.45
My question is why isn't numerator being stored as a 5x1 array like xval and yval??
 
Physics news on Phys.org
Anthony LaRosa said:
My question is why isn't numerator being stored as a 5x1 array like xval and yval??
Because nansum of a 5x1 array returns a scalar.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 65 ·
3
Replies
65
Views
9K