Newbie question about table indexing,loops and logical arguments (should be easy)

1 次查看(过去 30 天)
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!

回答(2 个)

Jos (10584)
Jos (10584) 2016-6-3
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

Stephen23
Stephen23 2016-6-3
编辑:Stephen23 2016-6-3
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).

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by