Filter löschen
Filter löschen

if else, for loop, working with character variables

3 Ansichten (letzte 30 Tage)
Binzi Shu
Binzi Shu am 2 Mär. 2016
Kommentiert: Kirby Fears am 4 Mär. 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.

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by