Trouble saving concatenated nifti's in matlab

I am trying to concatenate two nifti files together in matlab. To do this, I open both nifti files, concatenate the volumes along the last dimension, then save with niftiwrite(volume,‘filename’). However, upon trying to save with niftiwrite, I am repeatedly getting this error:

Error using images.internal.nifti.niftiImage/writeHeader

Cannot open file for writing header.

I can’t find anything about it online, on this forum, or on matlab’s forum. Any ideas?

Best,
Hank

Hi @hankghgold,

Does filename include .nii.gz? That may be required. If the file name argument includes the full path, you should make sure that full directory tree exists. But I do not use MATLAB - this can be also be done pretty handily in python with Nibabel/Nilearn if you are not tied to MATLAB.

Best,
Steven

Hello Steven,

Thank you! I’ll try that out and get back to you. I’m not fully tied to matlab, but i know my PI prefers this done in matlab if possible.

Including .gz didn’t work :confused:

Hi @hankghgold,

To clarify, did you include .nii.gz or just .gz? Also what is the contents of volume ?

Best,
Steven

Hi Steven,

.nii.gz, and the contents of volume are 4d images.

Best,
Hank

Can you be more specific about what you mean by an image? It looks like it only expects numeric 3/4d data arrays for the main argument (that is, not image objects or anything extra like metadata), is that what you have?