Writing a cell array to excel but skipping certain values

5 visualizzazioni (ultimi 30 giorni)
I am currently working on code that will write values from a x*1 cell array to an excel file. I need to write each 15th value to an excel file (this I have managed to do).
This is what I am using to write each 15th cell in the cell array: x_new=X(15:15:end); xlswrite('test.xlsx', X_new)
Now, what I need help with is to some code to this that will let me be able to skip certain values of this x*1 cell array. I want to write each 15th value, but I want to skip all 0 values. However, I cannot remove the 0 values before I write to excel. I need to write each 15th value to excel, but if it is ever 0 (if number cell number 15, 30 or 45 is zero) then that should be skipped and the next value (not zero) should be written instead, before it goes back to writing each 15th cell.
Is this clear? I do not have much experience with matlab, and I am using it to collect data for my master thesis.

Risposte (1)

Sarah Wait Zaranek
Sarah Wait Zaranek il 20 Feb 2012
I think it is clear what you want to do- I don't have MATLAB open, so forgive minor syntax issues.
1. Step one extract the every 15th points
x_new = X(15:15:end);
x_new = cell2mat(x_new); %changing into double array
x_idx = ((1:length(x_new))) * 15; % index in ref to x
2. Find if any zeros exist
ind = find(x_new==0);
3. Replace existing values with idx + 1 values
x_new(ind) = [X{x_idx(ind)+1}];
4. Write out x_new to excel
** Edited **
New version of code including check if x_new is a cell array
%%New version of the code
X = num2cell(rand(500,1));
X{15} = 0;
X{135} = 0;
X{300} = 0;
x_new = X(15:15:end);
% Make sure you are working with a cell array
if iscell(x_new)
x_new = X(15:15:end);
x_new = cell2mat(x_new); %changing into double array
x_idx = ((1:length(x_new))) * 15; % index in ref to x
ind = find(x_new==0);
x_new(ind) = [X{x_idx(ind)+1}];
else
disp('Your variable not a cell')
end
  8 Commenti
Sarah Wait Zaranek
Sarah Wait Zaranek il 8 Mar 2012
I assume that the value next to the zero is not a zero. If it is a zero, you need to do a check and advance one more.
Magnus
Magnus il 12 Mar 2012
I managed, with help, to solve my problem, thank you for your answer =)

Accedi per commentare.

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by