You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单命令创建m×n大小的Octave矩阵并填充初始值

Creating m×n Octave Matrices with Default/Initial Values (One-Line Commands)

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 the zeros() function—super straightforward for initializing matrices with all zeros:

    A = zeros(m, n);  % Swap m for your desired row count, n for column count
    

    Example: 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 value
    

    Alternatively, 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);
      
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:28:18