if else, for loop, working with character variables

3 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by