Matlab未定义变量 [英] Matlab undefined variable

查看:89
本文介绍了Matlab未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下代码:

[w1, d1]=fit1; 
    for i = 1:10, 
      p = w1*d1+i;
      C(i,:) = p;
    end

[w2, d2]=fit2; 
    for i = 1:10, 
      q = w2*d2+i;
      D(i,:) = q;
    end

其中函数 fit1 :

function[w1, d1] = fit1
w1 = rand(1);
d1 = rand(1);

和函数 fit2 :

function[w2, d2] = fit2
w2 = w1+0.2;
d2 = d1-0.1;

我收到错误:未定义的函数或变量w1".

但是参数 w1 是在调用 fit2 之前定义的,为什么这不起作用?

But the parameter w1 is defined before fit2 is called so why doesn't this work?

谢谢!

推荐答案

这是因为您的函数 fit2 不知道变量 w1 d1 .每个函数都有其自己的变量空间,该变量空间由输入自变量以及该函数内部定义的变量组成.函数 fit2 没有任何输入,因此不知道任何变量.为了使代码正常工作,您应该将 fit2 修改为具有2个输入(您将在此函数内部使用):

This is because your function fit2 doesn't know variables w1 and d1. Every function has it's own variable space, which consists of input arguments and, of course, variables defined inside this function. Function fit2 doesn't have any inputs, therefore it doesn't know any variable. In order your code to work, you should modify fit2 to have 2 inputs (which you are using inside this function):

function[w2, d2] = fit2(w1,d1)
w2 = w1+0.2;
d2 = d1-0.1;

并使用输入参数进行调用:

And call it with it's input arguments:

[w2, d2]=fit2(w1,d1);

这篇关于Matlab未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆