> traindata <- d$close[index==2022,] Error in d$close[index == 2022, ] : incorrect number of dimensions
时间: 2024-03-11 18:49:05 浏览: 73
这个错误是因为在你使用下标运算符`[]`时,你提供的索引 `index==2022` 返回的是一个逻辑向量,而不是一个完整的整数向量或索引向量。
要解决这个问题,请确保使用的索引是一个完整的整数向量,例如:
```
traindata <- d$close[index == 2022, ]
```
或者,你可以使用 `which()` 函数来将逻辑向量转换为整数向量:
```
traindata <- d$close[which(index == 2022), ]
```
这将返回 `d$close` 中在 `index` 中等于 2022 的元素。
相关问题
index <- sample(length(d$close),replace = TRUE,prob=c(0.7,0.3)) Error in sample.int(x, size, replace, prob) : incorrect number of probabilities
这个错误是因为你提供的概率向量的长度不正确。在这个例子中,你提供了一个长度为 2 的概率向量,但你采样的数据长度可能大于 2,这就导致了错误。
请确保提供的概率向量的长度与你要采样的数据长度相匹配,或者使用不提供概率向量的方式进行采样,例如:
```
index <- sample(length(d$close), replace = TRUE)
```
这将在数据长度内随机生成索引,不考虑任何概率权重。
matlab代码function probeData(varargin)if (nargin == 1) settings = deal(varargin{1}); fileNameStr = settings.fileName; elseif (nargin == 2) [fileNameStr, settings] = deal(varargin{1:2}); if ~ischar(fileNameStr) error('File name must be a string'); end else error('Incorect number of arguments'); end[fid, message] = fopen(fileNameStr, 'rb'); if (fid > 0) % Move the starting point of processing. Can be used to start the % signal processing at any point in the data record (e.g. for long % records). fseek(fid, settings.skipNumberOfBytes, 'bof'); % Find number of samples per spreading code samplesPerCode = round(settings.samplingFreq / ... (settings.codeFreqBasis / settings.codeLength)); if (settings.fileType==1) dataAdaptCoeff=1; else dataAdaptCoeff=2; end % Read 100ms of signal [data, count] = fread(fid, [1, dataAdaptCoeff100samplesPerCode], settings.dataType); fclose(fid); if (count < dataAdaptCoeff100samplesPerCode) % The file is to short error('Could not read enough data from the data file.'); end %--- Initialization --------------------------------------------------- figure(100); clf(100); timeScale = 0 : 1/settings.samplingFreq : 5e-3; %--- Time domain plot ------------------------------------------------- if (settings.fileType==1) subplot(2, 2, 3); plot(1000 * timeScale(1:round(samplesPerCode/2)), ... data(1:round(samplesPerCode/2))); axis tight; grid on; title ('Time domain plot'); xlabel('Time (ms)'); ylabel('Amplitude'); else data=data(1:2:end) + 1i .* data(2:2:end); subplot(3, 2, 4); plot(1000 * timeScale(1:round(samplesPerCode/2)), ... real(data(1:round(samplesPerCode/2)))); axis tight; grid on; title ('Time domain plot (I)'); xlabel('Time (ms)'); ylabel('Amplitude'); subplot(3, 2, 3); plot(1000 * timeScale(1:round(samplesPerCode/2)), ... imag(data(1:round(samplesPerCode/2)))); axis tight; grid on; title ('Time domain plot (Q)'); xlabel('Time (ms)'); ylabel('Amplitude'); end %--- Frequency domain plot -------------------------------------------- if (settings.fileType==1) %Real Data subplot(2,2,1:2); pwelch(data, 32768, 2048, 32768, settings.samplingFreq/1e6) else % I/Q Data subplot(3,2,1:2); [sigspec,freqv]=pwelch(data, 32768, 2048, 32768, settings.samplingFreq,'twosided'); plot(([-(freqv(length(freqv)/2:-1:1));freqv(1:length(freqv)/2)])/1e6, ... 10*log10([sigspec(length(freqv)/2+1:end); sigspec(1:length(freqv)/2)])); end axis tight; grid on; title ('Frequency domain plot'); xlabel('Frequency (MHz)'); ylabel('Magnitude'); %--- Histogram -------------------------------------------------------- if (settings.fileType == 1) subplot(2, 2, 4); hist(data, -128:128) dmax = max(abs(data)) + 1; axis tight; adata = axis; axis([-dmax dmax adata(3) adata(4)]); grid on; title ('Histogram'); xlabel('Bin'); ylabel('Number in bin'); else subplot(3, 2, 6); hist(real(data), -128:128) dmax = max(abs(data)) + 1; axis tight; adata = axis; axis([-dmax dmax adata(3) adata(4)]); grid on; title ('Histogram (I)'); xlabel('Bin'); ylabel('Number in bin'); subplot(3, 2, 5); hist(imag(data), -128:128) dmax = max(abs(data)) + 1; axis tight; adata = axis; axis([-dmax dmax adata(3) adata(4)]); grid on; title ('Histogram (Q)'); xlabel('Bin'); ylabel('Number in bin'); end else %=== Error while opening the data file ================================ error('Unable to read file %s: %s.', fileNameStr, message); end % if (fid > 0)翻译成python
抱歉,由于MATLAB和Python的语法和结构有所不同,将MATLAB代码翻译成Python代码需要对代码进行一定程度的重构和修改。以下是一个可能的Python代码实现,仅供参考:
```python
import numpy as np
import matplotlib.pyplot as plt
def probeData(*args):
if len(args) == 1:
settings = args[0]
fileNameStr = settings['fileName']
elif len(args) == 2:
fileNameStr, settings = args
if not isinstance(fileNameStr, str):
raise ValueError('File name must be a string')
else:
raise ValueError('Incorrect number of arguments')
with open(fileNameStr, 'rb') as fid:
# Move the starting point of processing.
# Can be used to start the signal processing at any point in the data record (e.g. for long records).
fid.seek(settings['skipNumberOfBytes'], 0)
# Find number of samples per spreading code
samplesPerCode = round(settings['samplingFreq'] / (settings['codeFreqBasis'] / settings['codeLength']))
if settings['fileType'] == 1:
dataAdaptCoeff = 1
else:
dataAdaptCoeff = 2
# Read 100ms of signal
data = np.fromfile(fid, dtype=settings['dataType'], count=dataAdaptCoeff*100*samplesPerCode)
fid.close()
if len(data) < dataAdaptCoeff*100*samplesPerCode:
# The file is too short
raise ValueError('Could not read enough data from the data file.')
#--- Initialization ---------------------------------------------------
plt.figure(100)
plt.clf()
timeScale = np.arange(0, 5e-3, 1/settings['samplingFreq'])
#--- Time domain plot -------------------------------------------------
if settings['fileType'] == 1:
plt.subplot(2, 2, 3)
plt.plot(1000*timeScale[:round(samplesPerCode/2)], data[:round(samplesPerCode/2)])
plt.axis('tight')
plt.grid(True)
plt.title('Time domain plot')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
else:
data = data[::2] + 1j*data[1::2]
plt.subplot(3, 2, 4)
plt.plot(1000*timeScale[:round(samplesPerCode/2)], np.real(data[:round(samplesPerCode/2)]))
plt.axis('tight')
plt.grid(True)
plt.title('Time domain plot (I)')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
plt.subplot(3, 2, 3)
plt.plot(1000*timeScale[:round(samplesPerCode/2)], np.imag(data[:round(samplesPerCode/2)]))
plt.axis('tight')
plt.grid(True)
plt.title('Time domain plot (Q)')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
#--- Frequency domain plot --------------------------------------------
if settings['fileType'] == 1:
#Real Data
plt.subplot(2, 2, 1)
plt.subplot(2, 2, 2)
f, Pxx = signal.welch(data, fs=settings['samplingFreq'], nperseg=32768, noverlap=2048, nfft=32768)
plt.plot(f/1e6, 10*np.log10(Pxx))
else:
# I/Q Data
plt.subplot(3, 2, 1)
plt.subplot(3, 2, 2)
f, Pxx = signal.welch(data, fs=settings['samplingFreq'], nperseg=32768, noverlap=2048, nfft=32768, return_onesided=False)
plt.plot((np.concatenate((-f[len(f)//2:], f[:len(f)//2])))/1e6, 10*np.log10(np.concatenate((Pxx[len(Pxx)//2:], Pxx[:len(Pxx)//2]))))
plt.axis('tight')
plt.grid(True)
plt.title('Frequency domain plot')
plt.xlabel('Frequency (MHz)')
plt.ylabel('Magnitude')
#--- Histogram --------------------------------------------------------
if settings['fileType'] == 1:
plt.subplot(2, 2, 4)
plt.hist(data, bins=np.arange(-128, 129))
dmax = np.max(np.abs(data)) + 1
plt.axis([-dmax, dmax, *plt.axis()[2:]])
plt.grid(True)
plt.title('Histogram')
plt.xlabel('Bin')
plt.ylabel('Number in bin')
else:
plt.subplot(3, 2, 6)
plt.hist(np.real(data), bins=np.arange(-128, 129))
dmax = np.max(np.abs(data)) + 1
plt.axis([-dmax, dmax, *plt.axis()[2:]])
plt.grid(True)
plt.title('Histogram (I)')
plt.xlabel('Bin')
plt.ylabel('Number in bin')
plt.subplot(3, 2, 5)
plt.hist(np.imag(data), bins=np.arange(-128, 129))
dmax = np.max(np.abs(data)) + 1
plt.axis([-dmax, dmax, *plt.axis()[2:]])
plt.grid(True)
plt.title('Histogram (Q)')
plt.xlabel('Bin')
plt.ylabel('Number in bin')
```
阅读全文