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

Matlab中stem函数报错(X与Y长度需一致):求解数组奇偶部

解决Matlab中「Error using stem X must be same length as Y」报错

错误根源是函数调用时参数顺序颠倒:你定义的函数fun(t,x)中,第一个参数t对应横轴坐标数组(即你的n1),第二个参数x对应信号数组,但调用时写的是fun(x,n1),导致t接收了信号数组x,x接收了横轴数组n1,触发了stem函数的输入长度匹配错误。

修正后的完整代码如下:

close all;
clear all;
clc;

n1 = -5:1:5;
AM = 19390;
x = [1,9,3,9,0,1,1,9,3,9,0];
fun(n1,x); % 修正参数顺序,将横轴数组n1作为第一个参数传入


function [sima,xr] = fun(t,x)  
      x_reverse = fliplr(x);% 时间反转
      sima = 0.5*(x + x_reverse); % 偶部分量
      xr = 0.5*(x - x_reverse); % 奇部分量
      subplot(3,1,1);
      stem(t,x);
      title('Your signal x')
      subplot(3,1,2); 
      stem(t,sima);
      title('Even part');
      subplot(3,1,3);
      stem(t,xr);
      title('Odd part');
end

关键说明:

  • 函数fun的参数定义t对应横轴坐标,x对应信号数组,调用时必须保证传入顺序与定义一致
  • 修正后stem(t,x)中,t(n1)和x长度均为11,完全满足stem函数对输入长度的匹配要求,同时逻辑上正确对应信号的横轴与纵轴

内容的提问来源于stack exchange,提问作者mantz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:45:27