Related
I'm trying to make a strategy of an indicator, but I get the error: Line 73: Cannot call 'operator >' with argument 'expr0'='call 'alertcondition' (void)'. An argument of 'void' type was used but a 'const float' is expected. How can I change the code to get a correct boolean if statement for the trade entry? I'm very new to pine, hopefully someone can help me.
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//#version=5
// Umgeschrieben von JSt
strategy("Watson Strategie Nadaraya-Watson Envelope [JSt]",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.float(500,'Window Size',maxval=500,minval=0)
h = input.float(8.,'Bandwidth')
mult = input.float(3.)
src = input.source(close,'Source')
up_col = input.color(#39ff14,'Colors',inline='col')
dn_col = input.color(#ff1100,'',inline='col')
//----
n = bar_index
var k = 2
var upper = array.new_line(0)
var lower = array.new_line(0)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length/k-1
array.push(upper,line.new(na,na,na,na))
array.push(lower,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)
sum_e = 0.
for i = 0 to length-1
sum = 0.
sumw = 0.
for j = 0 to length-1
w = math.exp(-(math.pow(i-j,2)/(h*h*2)))
sum += src[j]*w
sumw += w
y2 = sum/sumw
sum_e += math.abs(src[i] - y2)
array.push(y,y2)
mae = sum_e/length*mult
for i = 1 to length-1
y2 = array.get(y,i)
y1 = array.get(y,i-1)
up := array.get(upper,i/k)
dn := array.get(lower,i/k)
lset(up,n-i+1,y1 + mae,n-i,y2 + mae,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)
if src[i] > y1 + mae and src[i+1] < y1 + mae
label.new(n-i,src[i],'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
if src[i] < y1 - mae and src[i+1] > y1 - mae
label.new(n-i,src[i],'▲',color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)
cross_up := array.get(y,0) + mae
cross_dn := array.get(y,0) - mae
// TestUP = ta.crossover(src,cross_up) > 0
alertcondition(ta.crossover(src,cross_up),'Down','Down')
alertcondition(ta.crossunder(src,cross_dn),'Up','Up')
//---- Alarm für Webhook -----
plot(cross_up, color=#000000, transp=100) //Für den Alert, jedoch Darstellungsfehler → Transparent
plot(cross_dn, color=#000000, transp=100)
plotchar(cross_up, title="cross_up%", char="", location=location.top, color = color.green) // Damit der Wert in der Statusleiste dargestellt wird
plotchar(cross_dn, title="cross_dn%", char="", location=location.top, color = color.red)
//-------------------
// Start Date
// STEP 1. Create inputs that configure the backtest's date range
useDateFilter = input.bool(true, title="Begin Backtest at Start Date",
group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2021"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
// STEP 2. See if current bar happens on, or later than, the start date
inTradeWindow = not useDateFilter or time >= backtestStartDate
// ---------------
// Enter a long position when the entry rule is triggered
if inTradeWindow and ta.crossover(src,cross_up) > 0
strategy.entry('Long', strategy.long)
// Exit the Long position when the exit rule is triggered
if close > strategy.position_avg_price + 50
strategy.close("Long", comment = "TP")
else if close < strategy.position_avg_price - 50
strategy.close("Long", comment = "SL")
I tried the ta.crossover(src,cross_up) to compare it to zero, but it doesn't work.
ta.crossover() returns a bool value.
ta.crossover(source1, source2) → series bool
So, comparing its return value with some number does not make any sense and the compiler will complain: ta.crossover(src,cross_up) > 0.
You should just do:
if inTradeWindow and ta.crossover(src,cross_up)
strategy.entry('Long', strategy.long)
I have an mp3.txt file which contains URLs to download. How do I read the contents to then download the URLs? I tried this but it's not working:
Func _downloader($link)
Local $dwnarrayread[3] = [IniRead(#ScriptDir & "\mp3.txt", "file_links", "link_1", Default), IniRead(#ScriptDir & "\mp3-2.txt", "file_links", "link_2", Default), IniRead(#ScriptDir & "\mp3-3.txt", "file_links", "link_3", Default)]
$dwnlink = InetGet($dwnarrayread[$link], #ScriptDir & "PSU-04.mp3", 1, 1)
Do
Sleep(50)
$prc = Round(InetGetInfo($dwnlink, 0) / (InetGetInfo($dwnlink, 1)) * 100)
GUICtrlSetData($progressbar1, $prc)
Until InetGetInfo($dwnlink, $INET_DOWNLOADCOMPLETE)
EndFunc
mp3.txt file :
[files_links]
link_1=https://ftp.psu.ac.th/pub/demo/mp3/PSU-04.mp3
link_2=http://somesite.com/files/file2.zip
link_3=http://somesite.com/files/file3.zip
How do I read the contents to then download the URLs?
Example (as per additional requirement):
_Download('mp3.txt', 'files_links', #DesktopDir & '\')
Func _Download(Const $sFileIni, Const $sSection, Const $sDest)
Local Const $aFile = IniReadSection($sFileIni, $sSection)
For $i1 = 1 To $aFile[0][0]
InetGet($aFile[$i1][1], $sDest & StringTrimLeft($aFile[$i1][1], StringInStr($aFile[$i1][1], '/', 0, -1)))
Next
EndFunc
Example as per GUICtrlSetData() -attempt:
#include <AutoItConstants.au3>
#include <InetConstants.au3>
#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>
_Download('mp3.txt', 'files_links', #DesktopDir & '\')
Func _Download(Const $sFileIni, Const $sSection, Const $sDest)
Local Const $aFile = IniReadSection($sFileIni, $sSection)
Local $aDownload[$aFile[0][0] + 1]
$aDownload[0] = $aFile[0][0]
For $i1 = 1 To $aFile[0][0]
$aDownload[$i1] = InetGet($aFile[$i1][1], $sDest & StringTrimLeft($aFile[$i1][1], StringInStr($aFile[$i1][1], '/', 0, -1)), $INET_FORCERELOAD, $INET_DOWNLOADBACKGROUND)
Next
Local Const $iWidth = 400, _
$iHeight = 20
Local $hWnd = GUICreate(#ScriptName, $iWidth, $iHeight * $aDownload[0])
Local $aHnd[$aDownload[0] + 1]
For $i1 = 1 To $aDownload[0]
$aHnd[$i1] = GUICtrlCreateProgress(0, ($i1 - 1) * $iHeight, $iWidth, $iHeight)
GUICtrlSetTip($aHnd[$i1], $aFile[$i1][1])
Next
GUISetState(#SW_SHOW, $hWnd)
Local $aInfo
While Not (GUIGetMsg() = $GUI_EVENT_CLOSE)
For $i1 = 1 To $aDownload[0]
$aInfo = InetGetInfo($aDownload[$i1])
GUICtrlSetData($aHnd[$i1], ($aInfo[$INET_DOWNLOADCOMPLETE] Or $aInfo[$INET_DOWNLOADSUCCESS]) ? 100 : $aInfo[$INET_DOWNLOADSIZE] / $aInfo[$INET_DOWNLOADREAD])
Next
If InetGetInfo() Then ContinueLoop
MsgBox($MB_OK, #ScriptName, 'No more running downloads.', 0, $hWnd)
ExitLoop
WEnd
For $i1 = 1 To $aDownload[0]
InetClose($aDownload[$i1])
Next
EndFunc
*[I found that the error occurred at line 57, z2 = w12.a1 + b12; with incompatible array size,
May I know how to fix it? Basically the data is from the simulation on MATLAB Simulink, so the size of the array changes as we increase the inputs from the original code which only have 1 input type][1]
%% load training data (use training_data.mat attached file)
% initialize number of nodes, weights, biases, errors and gradients.
%epochs and mini-batch size
clc
data = [out.dutycycle out.voltage out.current]
sample=1000;
labels = data(1:sample,1);
y = labels'; %output vector
images = data(1:sample,2:3);
images(:,1) = images(:,1)/400;
images(:,2) = images(:,2)/100;
images = images'; %Input vectors
hn1 = 80; %Number of neurons in the first hidden layer
hn2 = 60; %Number of neurons in the second hidden layer
%Initializing weights and biases
w12 = randn(hn1,1000).*sqrt(2/1000);
w23 = randn(hn2,hn1)*sqrt(2/hn1);
w34 = randn(1,hn2)*sqrt(2/hn2);
b12 = randn(hn1,1);
b23 = randn(hn2,1);
b34 = randn(1,1);
%learning rate
eta = 0.0058;
%Initializing errors and gradients
error4 = zeros(1,1);
error3 = zeros(hn2,1);
error2 = zeros(hn1,1);
errortot4 = zeros(1,1);
errortot3 = zeros(hn2,1);
errortot2 = zeros(hn1,1);
grad4 = zeros(1,1);
grad3 = zeros(hn2,1);
grad2 = zeros(hn1,1);
epochs = 50;
m = 10; %Minibatch size
%% Training phase
for k = 1:epochs %Outer epoch loop
batches = 1;
for j = 1:sample/m
error4 = zeros(1,1);
error3 = zeros(hn2,1);
error2 = zeros(hn1,1);
errortot4 = zeros(1,1);
errortot3 = zeros(hn2,1);
errortot2 = zeros(hn1,1);
grad4 = zeros(1,1);
grad3 = zeros(hn2,1);
grad2 = zeros(hn1,1);
for i = batches:batches+m-1 %Loop over each minibatch
%Feed forward
a1 = images(:,i);
z2 = w12.*a1 + b12;
a2 = elu(z2);
z3 = w23*a2 + b23;
a3 = elu(z3);
z4 = w34*a3 + b34;
a4 = elu(z4); %Output vector
%backpropagation
error4 = (a4-y(:,i)).*elup(z4);
error3 = (w34'*error4).*elup(z3);
error2 = (w23'*error3).*elup(z2);
errortot4 = errortot4 + error4;
errortot3 = errortot3 + error3;
errortot2 = errortot2 + error2;
grad4 = grad4 + error4*a3';
grad3 = grad3 + error3*a2';
grad2 = grad2 + error2*a1';
end
%Gradient descent
w34 = w34 - eta/m*grad4;
w23 = w23 - eta/m*grad3;
w12 = w12 - eta/m*grad2;
b34 = b34 - eta/m*errortot4;
b23 = b23 - eta/m*errortot3;
b12 = b12 - eta/m*errortot2;
batches = batches + m;
end
fprintf('Epochs:');
disp(k) %Track number of epochs
[images,y] = shuffle(images,y); %Shuffles order of the images for next epoch
end
disp('Training done!')
%note : create folder for this experiment and save the parameters.
% don't forget to keep the folder in matlab path!
save('wfour.mat','w34');
save('wthree.mat','w23');
save('wtwo.mat','w12');
save('bfour.mat','b34');
save('bthree.mat','b23');
save('btwo.mat','b12');
%% Testing phase
% load testing data with labels ... (use testing_data.mat attached file)
testsample = 100;
labels = test(1:testsample,1);
y = labels';
images = test(1:testsample,2:3);
images(:,1) = images(:,1)/400;
images(:,2) = images(:,2)/100;%copy
images = images';
we34 = matfile('wfour.mat');
w4 = we34.w34;
we23 = matfile('wthree.mat');
w3 = we23.w23;
we12 = matfile('wtwo.mat');
w2 = we12.w12;
bi34 = matfile('bfour.mat');
b4 = bi34.b34;
bi23 = matfile('bthree.mat');
b3 = bi23.b23;
bi12 = matfile('btwo.mat');
b2 = bi12.b12;
success = 0;
n = testsample;
for i = 1:n
out2 = elu(w2*images(:,i)+b2);
out3 = elu(w3*out2+b3);
out = elu(w4*out3+b4);
big = 0;
num = 0;
for k = 1:10
if out(k) > big
num = k-1;
big = out(k);
end
end
if labels(i) == num
success = success + 1;
end
end
fprintf('Accuracy: ');
fprintf('%f',success/n*100);
disp(' %');
%% ELU activation function
function fr = elu(x)
f = zeros(length(x),1);
for i = 1:length(x)
if x(i)>=0
f(i) = x(i);
else
f(i) = 0.2*(exp(x(i))-1);
end
end
fr = f;
end
%% derivative of the ELU activation function
function fr = elup(x)
f = zeros(length(x),1);
for i = 1:length(x)
if x(i)>=0
f(i) = 1;
else
f(i) = 0.2*exp(x(i));
end
end
fr = f;
end
%% SHuffle function
function [B,v] = shuffle(A,y)
cols = size(A,2);
P = randperm(cols);
B = A(:,P);
v = y(:,P);
end
Your help is much appreciated, thank you
MATLAB Error :
Arrays have incompatible sizes for this operation.
Error in ANN_PV_Array (line 57)
z2 = w12.*a1 + b12;
J1 = 18.041;
J2 = 1.99;
J3 = 6.58;
J4 = 1.46;
J5 = 7.50;
J6 = 15.46;
J7 = 4.21;
J8 = 7.68;
J9 = 24.84;
J10 = 8.58;
J11 = 6.57;
J12 = 4.20;
J13 = 4.63;
J14 = 0.7648;
J15 = 0.3607;
J16 = 68.48;
Js1 = 145.09;
Js2 = 128.58;
Js3 = 138.841;
Js4 = 145.09;
Jcar = 1.7916;
Jhollow = 1.478;
r1 = 45;
r2 = 46;
r3 = 38;
r4 = 15;
r5 = 37;
r6 = 68;
r7 = 29;
r8 = 37;
r9 = 60;
r10 = 33;
r11 = 29;
r12 = 27;
r13 = 52;
r14 = 19;
r15 = 16;
r16 = 57;
k0 = 241.32;
w2 = 1000;
kcar = 0.356;
khollow = 6.091;
D = 4867.91;
%syms h3(t) x3(t) theta2(t) theta1(t) x2(t) h4(t) h5(t) h1(t) h2(t) x1(t)
%ode1 = diff(h3)- (J4*r9*(diff(theta2,2)))/r4 == (theta2*khollow*r9)/r4 - kcar*theta1;
%ode2 = diff(x3,t) - (h3/J8)*r8 + w2*r3 == 0;
%ode3 = diff(x2,t) - (h2/J10)*r10 + w2*r5 == 0;
%ode4 = diff(theta2,t)*(r4- 1/(k0*r4)) - (diff(theta2,t,3)/(k0*r4)) - h3*r9/(J9 + Js1) + w2*r4 == 0;
%ode5 = diff(h1,t) - D*r16*(diff(x1)) == k0*x1*r16 - D*r16*((h4*r14)/(Js2 + J1 + (Jcar/3)));
%ode6 = diff(x1,t) - (h4)*r14/(Js2 + J1 + (Jcar/3)) + h1*r16/J16 == 0;
%ode7 = diff(h5,t) - x3*k0*r8 == 0;
%ode8 = diff(h2,t) - x2*k0*r10 == 0;
%ode9 = diff(h4,t) - kcar*theta1 - (2*h4*D)/(Js2 + J1 + (Jcar/3)) + k0*x1*r14 == 0;
%ode10 = diff(theta1,t) - h3/(J9 + Js1) + (h4)/(Js2 + J1 + (Jcar/3)) == 0;
%odes = [ode1; ode2; ode3; ode4; ode5; ode6; ode7; ode8; ode9; ode10];
%S = dsolve(odes);
f = #(t,x) [(J4*r9*(diff(x(4),2)))/r4 + (x(4)*khollow*r9)/r4 - kcar*x(10);
(x(1)*r8)/(J8) - w2*r3;
(x(8)/J10)*r10 - w2*r5;
(x(1)*r9)/(J9 + Js1)*r4 + (diff(x(4)) + diff(x(4),3))/(k0*r4*r4) - w2;
k0*x(6)*r16 - D*r16*(((x(9))*r14)/(Js2 + J1 + (Jcar/3)) - diff(x(6)));
(x(9)*r14)/(Js2 + J1 + (Jcar/3)) - (x(5)*r16)/J16;
x(2)*k0*r8;
x(3)*k0*r10;
kcar*x(10) - x(9)*2*D/(Js1 + J1 + (Jcar/3)) -k0*x(6)*r14;
x(1)/(J9 + Js1) - x(9)/(Js2 + J1 + (Jcar/3))];
[t,xa] = ode45(f,[0 1.5], [0 2 2 2 2 3 1 9 9 1])
Array dimensions are not consistent matlab output error. The commented out code runs for a long time and has not outputted results after running it for 15-20 minutes. The differentials equations are solved using ODE 45. Would really appreciate some help on this. The differential equations come from analyzing a dual clutch manual transmission using the bond graph technique.
Before putting a function like f into ode, try it. It is already broken and you get the same error when calling f(t,x). Further debugging it, evaluate the lines of f one by one:
>> (J4*r9*(diff(x(4),2)))/r4 + (x(4)*khollow*r9)/r4 - kcar*x(10)
ans =
[]
>> (x(1)*r8)/(J8) - w2*r3
ans =
-38000
The first row holds 0 elements, the second 1 element. I did not continue but this is already a problem. Each row has to have the same number of elements, probably 1 in your case.
In one of my GUIs I load DICOM images. Sometimes they are just a volume and another dimension and when I load them in Matlab everything ends up where I want it.
handles.inf = dicominfo([filepath filename]);
handles.dat = dicomread(handles.inf);
size(handles.dat)
ans = 128 128 128 512
For an 128 by 128 by 128 volume at 512 timepoints for example (actually the third dimension would not even be 128, the third dimension is stacks, of which I don't know what it is). However sometimes There are more dimensions in the dicom, but the reader just puts all of them in the fourth dimension.
handles.inf = dicominfo([filepath filename]);
handles.dat = dicomread(handles.inf);
size(handles.dat)
ans = 128 128 1 4082
For a single 128 by 128 slice with 512 timepoints, two echoes and magnitude, phase, real and imaginary data for example.
It is then very hard to unscramble them. Manually I can do this for every DICOM I load but when in a GUI I would want to have a general approach that just creates a dimension in the array for each dimension in the dicom.
This is especially important not just for data-analysis, but also to transform the coordinates from image space to patient space. My own approach was to look at the header, but there's no guarantee that certain entries will work, and the order in which they are applied I can't find. The header entries I found so far:
inf.Rows;%inf.width;%inf.MRAcquisitionFrequencyEncodingSteps;%inf.MRAcquisitionPhaseEncodingStepsInPlane
inf.Columns;% inf.height; % inf.NumberOfKSpaceTrajectories;
inf.MRSeriesNrOfSlices
inf.MRSeriesNrOfEchoes
inf.MRSeriesNrOfDynamicScans
inf.MRSeriesNrOfPhases
inf.MRSeriesReconstructionNumber % not sure about this one
inf.MRSeriesNrOfDiffBValues
inf.MRSeriesNrOfDiffGradOrients
inf.MRSeriesNrOfLabelTypes
reshapeddat = reshape(dat, [all dimension sizes from header here]);
I'm not sure how to check if I've got all variables and what the right order for the reshape. Anybody knows of a sure-fire way to get all dimension sizes from the DICOM header and the order in which they are stacked?
Ok so I now manually go by all possible dimensions. When a stack also contains reconstructed data which has less dimensions than the rest, remove those first.
This is how I check the dimensions:
info = dicominfo(filename);
datorig = dicomread(filename);
%dimension sizes per frame
nrX = double(info.Rows); %similar nX;% info.width;% info.MRAcquisitionFrequencyEncodingSteps;% info.MRAcquisitionPhaseEncodingStepsInPlane
nrY = double(info.Columns); %similar nY;% info.height;% info.NumberOfKSpaceTrajectories;
%dimensions between frames
nrEcho = double(info.MRSeriesNrOfEchoes);
nrDyn = double(info.MRSeriesNrOfDynamicScans);
nrPhase = double(info.MRSeriesNrOfPhases);
nrSlice = double(info.MRSeriesNrOfSlices); %no per frame struct entry, calculate from offset.
%nr of frames
nrFrame = double(info.NumberOfFrames);
nrSeq = 1; % nSeq not sure how to interpret this, wheres the per frame struct entry?
nrBval = double(info.MRSeriesNrOfDiffBValues); % nB
nrGrad = double(info.MRSeriesNrOfDiffGradOrients); % info.MRSeriesNrOfPhaseContrastDirctns;%similar nGrad?
nrASL = 1; % info.MRSeriesNrOfLabelTypes;%per frame struct entry?
imtype = cell(1, nrFrame);
for ii = 1:nrFrame
%imtype(ii) = eval(sprintf('info.PerFrameFunctionalGroupsSequence.Item_%d.PrivatePerFrameSq.Item_1.MRImageTypeMR', ii));
imtype{ii} = num2str(eval(sprintf('info.PerFrameFunctionalGroupsSequence.Item_%d.PrivatePerFrameSq.Item_1.MRImageTypeMR', ii)));
end
imType = unique(imtype, 'stable');
nrType = length(imType);
This is how I reformat the dimensions:
%% count length of same dimension positions from start
if nrEcho > 1
for ii = 1:nrFrame
imecno(ii) = eval(sprintf('inf.PerFrameFunctionalGroupsSequence.Item_%d.PrivatePerFrameSq.Item_1.EchoNumber', ii));
end
lenEcho = find(imecno ~= imecno(1), 1, 'first') - 1;
else
lenEcho = nrFrame;
end
if nrDyn > 1
for ii = 1:nrFrame
imdynno(ii) = eval(sprintf('inf.PerFrameFunctionalGroupsSequence.Item_%d.PrivatePerFrameSq.Item_1.TemporalPositionIdentifier', ii));
end
lenDyn = find(imdynno ~= imdynno(1), 1, 'first') - 1;
else
lenDyn = nrFrame;
end
if nrPhase > 1
for ii = 1:nrFrame
imphno(ii) = eval(sprintf('inf.PerFrameFunctionalGroupsSequence.Item_%d.PrivatePerFrameSq.Item_1.MRImagePhaseNumber', ii));
end
lenPhase = find(imphno~=imphno(1), 1, 'first') - 1;
else
lenPhase = nrFrame;
end
if nrType > 1
q = 1;
imtyno(1, 1) = q;
for ii = 2:nrFrame
if imtype{:, ii-1} ~= imtype{:, (ii)}
q = q+1;
end
imtyno(1, ii) = q;
%for jj = 1:nrType
%if imtype{:,ii} == imType{:,jj}
% imtyno(1, ii) = jj;
%end
%end
end
if q ~= nrType
nrType = q;
end
lenType = find(imtyno ~= imtyno(1), 1, 'first') - 1;
else
lenType = nrFrame;
end
% slices are not numbered per frame, so get this indirectly from location
% currently not sure if working for all angulations
for ii = 1:nrFrame
imslice(:,ii) = -eval(['inf.PerFrameFunctionalGroupsSequence.Item_',sprintf('%d', ii),'.PlanePositionSequence.Item_1.ImagePositionPatient']);
end
% stdsl = std(imslice,[],2); --> Assumption
% dirsl = max(find(stdsl == max(stdsl)));
imslices = unique(imslice', 'rows')';
if nrSlice > 1
for ii = 1:nrFrame
for jj = 1:nrSlice
if imslice(:,ii) == imslices(:,nrSlice - (jj-1)); %dirsl or :?
imslno(1, ii) = jj;
end
end
end
lenSlice = find(imslno~=imslno(1), 1, 'first')-1;
else
lenSlice = nrFrame;
end
if nrBval > 1
for ii = 1:nrFrame
imbno(ii) = eval(sprintf('inf.PerFrameFunctionalGroupsSequence.Item_%d.PrivatePerFrameSq.Item_1.MRImageDiffBValueNumber', ii));
end
lenBval = find(imbno~=imbno(1), 1, 'first') - 1;
else
lenBval = nrFrame;
end
if nrGrad > 1
for ii = 1:nrFrame
imgradno(ii) = eval(sprintf('inf.PerFrameFunctionalGroupsSequence.Item_%d.PrivatePerFrameSq.Item_1.MRImageGradientOrientationNumber', ii));
end
lenGrad = find(imgradno~=imgradno(1), 1, 'first')-1;
else
lenGrad = inf.NumberOfFrames;
end
lenSeq = nrFrame; % dont know how to get this information per frame, in my case always one
lenASL = nrFrame; % dont know how to get this information per frame, in my case always one
%this would have been the goal format
goaldim = [nrSlice nrEcho nrDyn nrPhase nrType nrSeq nrBval nrGrad nrASL]; % what we want
goallen = [lenSlice lenEcho lenDyn lenPhase lenType lenSeq lenBval lenGrad lenASL]; % what they are
[~, permIX] = sort(goallen);
dicomdim = zeros(1, 9);
for ii = 1:9
dicomdim(1, ii) = goaldim(permIX(ii));
end
dicomdim = [nrX nrY dicomdim];
%for any possible zero dimensions from header use a 1 instead
dicomdim(find(dicomdim == 0)) = 1;
newdat = reshape(dat, dicomdim);
newdim = size(newdat);
newnonzero = length(newdim(3:end));
goalnonzero = permIX(1:newnonzero);
[dummyy, goalIX] = sort(goalnonzero);
goalIX = [1 2 goalIX+2];
newdat = permute(newdat, goalIX);
newdat = reshape(newdat, [nrX nrY goaldim]);
When Ive used this as a function for a longer period and debugged it a bit I might post in on the file exchange of mathworks.