if else, for loop, working with character variables
1 次查看(过去 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.
0 个评论
采纳的回答
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 个评论
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 Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!