Passing input variables to function

78 ビュー (過去 30 日間)
Hamza
Hamza 2014 年 4 月 28 日
コメント済み: Hamza 2014 年 4 月 28 日
Hi,
I am working on a script in which I define variables that then get passed onto a function to do further calculations with.
I am able to pass numerical values across but when I try to pass on a string of say 'yellow' across to the function I get the following error message ' In an assignment A(I) = B, the number of elements in B and I must be the same.'
I was wondering if anyone could point me towards the right approach to take when passing text between Matlab function.
Many thanks in advance.
Hamza
  4 件のコメント
Hamza
Hamza 2014 年 4 月 28 日
Hi Mischa,
Would this help?
m-file:
number_jackets = 5
colour = 'yellow'
var(1) = number_jackets
var(2) = colour
func = trial(var)
In this example I am trying to pass across the number of jackets and the colour of the jackets.
Is this what you were asking for?
Hamza
dpb
dpb 2014 年 4 月 28 日
Close enough... :)

サインインしてコメントする。

採用された回答

dpb
dpb 2014 年 4 月 28 日
OK, you're needing a cell array to hold the disparate types in one array. Write
var{1} = number_jackets;
var{2} = colour;
instead. NB: the "curlies", the '{}' instead of parens to create the cell array.
For such a case, as it'll be highly likely you'll want to access the two in the function rather than combine in a cell I'd probably either
a) pass them separately, particularly if they're going to be the only arguments to the function, or
b) make the related stuff into a structure with named fields for the clothing article
  1 件のコメント
Hamza
Hamza 2014 年 4 月 28 日
Thank you very much dpb, the curlies did the trick! :)
Hamza

サインインしてコメントする。

その他の回答 (1 件)

Niklas Nylén
Niklas Nylén 2014 年 4 月 28 日
編集済み: Niklas Nylén 2014 年 4 月 28 日
The problem is that you are trying to put mixed data types (one number and one string) into the same vector. If you use a cell instead, by replacing () with {} this is possible:
number_jackets = 5
colour = 'yellow'
var{1} = number_jackets
var{2} = colour
You will need to use {} when accessing the elements again.
myJacketColor = var{2}
Another way is to pass them as two separate arguments
func = trial(number_jackets, colour)
  1 件のコメント
Hamza
Hamza 2014 年 4 月 28 日
Thank you very much Niklas!
Hamza

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by