Newbie question about table indexing,loops and logical arguments (should be easy)
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hello all,
Lets say I have a table with two variables. X contains either characters or various empty cells(,) like so: X = [A , , B , , , C ...] and Y contains a logical argument indicating if there are characters in X, like so: Y = [1 0 0 1 0 0 0 1 ...]. Now, I want to fill the empty cells in X for a new variable (Z) so the empty cells always contain the character in the cell above like so: Z = [A A A B B B B, C ...].
So far my code looks like this:
if table.Y == 1
table.Z = table.X (so far so good)
else table.Z = ? (and Im stuck...
I need to tell Matlab "go one up above in X and assign that value in Z" something like:
table.Z = table.X(i-1)...
Any ideas?
Thanks all for your patience!
0 comentarios
Respuestas (2)
Jos (10584)
el 3 de Jun. de 2016
I am not sure how you store your data. Here is an example with a cell array
X = {'A','','','B','B','','C','C',''}
Y = [1 , 0, 0, 1 , 1 ,0 , 1 , 1 , 0] % you can do without this one
Z = cell(size(A))
lastidx = 1 ;
Z{1} = A{1}
for k=2:N
if Y(k)==0, % you could use isempty(A{k}) here
Z{k} = A{lastidx}
else
Z{k} = A{k}
lastidx = k
end
end
0 comentarios
Stephen23
el 3 de Jun. de 2016
Editada: Stephen23
el 3 de Jun. de 2016
There is no need to waste time with an ugly loop:
>> X = {'A','','','B','B','','C','C',''};
>> idx = ~cellfun('isempty',X);
>> tmp = X(idx);
>> X = tmp(cumsum(idx))
X =
'A' 'A' 'A' 'B' 'B' 'B' 'C' 'C' 'C'
Note that this code assumes that the first cell is not empty (otherwise it throws an error).
0 comentarios
Ver también
Categorías
Más información sobre Logical 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!