if else, for loop, working with character variables

1 visualización (últimos 30 días)
Binzi Shu
Binzi Shu el 2 de Mzo. de 2016
Comentada: Kirby Fears el 4 de Mzo. de 2016
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.

Respuesta aceptada

Kirby Fears
Kirby Fears el 2 de Mzo. de 2016
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 comentarios
Binzi Shu
Binzi Shu el 2 de Mzo. de 2016
yes it worked! Thanks! Could you brief talk about the difference btw {} and ()? Thanks again.
Kirby Fears
Kirby Fears el 4 de Mzo. de 2016
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by