如何用单命令创建m×n大小的Octave矩阵并填充初始值
Hey folks, let's break down all the clean, single-command ways to create an m×n matrix in Octave pre-filled with your desired initial values. These are the go-to methods you'll reach for regularly:
Zero-filled matrix (most common default)
Use thezeros()function—super straightforward for initializing matrices with all zeros:A = zeros(m, n); % Swap m for your desired row count, n for column countExample:
zeros(3, 4)spits out a 3-row, 4-column matrix where every element is 0.One-filled matrix
For a matrix packed with 1s,ones()is your quick solution:A = ones(m, n);Example:
ones(2, 5)creates a 2×5 matrix of all 1s.Matrix filled with a custom fixed value
If you want every element to be a specific number (like 9, for example), the shortest approach is to multiply a one-filled matrix by your target value:A = 9 * ones(m, n); % Replace 9 with your preferred valueAlternatively, you can use
repmat()for explicit repetition if you prefer:A = repmat(your_value, m, n);Both work, but the multiplication trick is more concise.
Random value matrices
Need random data? Octave has built-ins for different distributions:- Uniform random values between 0 and 1:
A = rand(m, n); - Normally distributed values (mean 0, variance 1):
A = randn(m, n); - Random integers in a range (e.g., 1 to 15):
A = randi([1, 15], m, n);
- Uniform random values between 0 and 1:
Identity matrix (or diagonal 1s for non-square)
For a matrix with 1s on the main diagonal and 0s elsewhere,eye()works for both square and rectangular matrices:A = eye(m, n);Example:
eye(3, 4)gives a 3×4 matrix where the first three diagonal elements are 1, and everything else is 0.
All these are single-line commands, so you can create and initialize your matrix in one fell swoop without extra steps.
内容的提问来源于stack exchange,提问作者Dror

