Azzera filtri
Azzera filtri

Simpler way of getting single column from each row?

2 visualizzazioni (ultimi 30 giorni)
I have a realitivly silly/simple question. I have a feeling there is no cleaner way to do this but I figured I'd ask.
So I have a group of waveforms stored in a nan array sized (number of waves, longest wave lenght) where each wave is a row in the array. Each wave begins at the start of the array and goes however long the wave is with the tail being nans. For example:
wave{1} = cos(2*pi*10*(0:1/1000:.25-(1/1000))'); % random wave 1
wave{2} = rand(100,1); % random wave 2
wave{3} = ([1 2 3 4 5 6 7 9 10]); % random wave 3
lengths = [length(wave{1}),length(wave{2}),length(wave{3})];
m = max(lengths);
waves = nan(3,m);
for i = 1:size(waves,1)
waves(i,1:lengths(i)) = wave{i};
end
On each wave I know a single index which contains a value (not a nan), say the max slope of the wave. (not a great measurement for these waves but this is just an example)
[diffpeaks_val, diffpeaks_idx] = max(diff(waves,1,2),[],2);
However these points are found from a different wave (like the diff). All that is shared between the two is the alignment of the indexs. I know that I can easily get the values in a for loop.
waveValues = zeros(length(diffpeaks_idx),2);
for i = 1:length(diffpeaks_idx)
waveValues(i,1) = diffpeaks_idx(i);
waveValues(i,2) = waves(i,diffpeaks_idx(i));
end
But i was wondering if there was a simpler way to get the value of the wave at the associated diffpeaks_idx. I played around with a few options, arrayFun and diag. While both are more terse then the original they are also harder to read. Although I haven't tested it, I'm guessing option #2 gets pretty slow the larger your array is since it's a nxn matrix where n=diffpeaks_idx len.
waveValues = [diffpeaks_idx arrayfun(@(i,x) waves(i,x), (1:length(diffpeaks_idx))', diffpeaks_idx)]; % array fun option
waveValues = [diffpeaks_idx diag(waves(:,diffpeaks_idx))] % diag option
Is there anything simpler anyone can think of? A more efficient version of the diag option would be pretty sweet something like
waves(:,diffpeaks_idx(:))
but I don't know that it exists.

Risposte (1)

Bob Thompson
Bob Thompson il 12 Feb 2019
Without having access to your data I can't test this, but my first thought is to do basically what you mentioned last.
waveValues(:,1) = diffpeaks_idx;
waveValues(:,2) = [waves{:,diffpeaks_idx}];
I don't know that this will work if diffpeaks_idx is an array. It should techinically still gather the values, but it's going to gather all columns for each wave, which is not what you want. I will think if there is a non-loop solution for wanting to call different columns, but I don't have one off the top of my head.

Community Treasure Hunt

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

Start Hunting!

Translated by