if else, for loop, working with character variables

1 回表示 (過去 30 日間)
Binzi Shu
Binzi Shu 2016 年 3 月 2 日
コメント済み: Kirby Fears 2016 年 3 月 4 日
z = Data(1:10,17) %take 10 numerical values into a new table, name of the variable is LOAN
for i = 1:height(z)
if z.LOAN(i)>300000
z.new(i) = 'pass'
else z.new(i) = 'fail'
end
end
So the above is giving me an error: In an assignment A(:) = B, the number of elements in A and B must be the same.
But if I change the above code to the following:
z = Data(1:10,17) %take 10 numerical values into a new table
for i = 1:height(z)
if z.LOAN(i)>300000
z.new(i) = 1
else z.new(i) = 0
end
end
Then the codes work fine. Why is it only working if I put 1/0 rather than pass/fail? How can I solve this? Thanks.

採用された回答

Kirby Fears
Kirby Fears 2016 年 3 月 2 日
Two questions:
1. Is z.new initialized before you start assigning values to it?
2. Did you try curly braces?
if z.LOAN(i)>300000,
z.new{i} = 'pass';
else
z.new{i} = 'fail';
end
  4 件のコメント
Binzi Shu
Binzi Shu 2016 年 3 月 2 日
yes it worked! Thanks! Could you brief talk about the difference btw {} and ()? Thanks again.
Kirby Fears
Kirby Fears 2016 年 3 月 4 日
Each variable in your table can be a numeric array or a cell array. For example, your LOAN variable is a numeric array.
When indexing a numeric array for value access or assignment, parentheses are used. However, curly braces are used to access or assign values in a cell array like z.new.
The difference is that a cell array contains cells while a double array contains the primitive double type. Parentheses work in a double array because you are assigning a double to a particular position in the array.
Parentheses work as well for cell arrays as long as you assign a cell to the indexed position.
For example:
z.new(1) = {'pass'}
But you cannot assign the character array 'pass' directly into the cell array because 'pass' is not a cell. Curly braces can be used to access or assign contents of a cell in the array:
z.new{1} = 'pass'
Hope this helps.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by